Home > Net >  how to write a csv file using a constant value in the file using R
how to write a csv file using a constant value in the file using R

Time:11-12

I have a data frame , use this dummy data frame as example

name = rep("ID1",3))
city = c("London", "Paris", "Tokio")
df = data.frame(name = name, city =  city)

I would like to export the data frame in a csv format (write_csv) but I would like to name it using the value in col name (ID1) as name ('automatically'):

write_csv(df, 'valueofthecolname_df.csv')

CodePudding user response:

Make the name you want by pasting pieces of text together:

write_csv(df, paste0(df$name[1], '_df.csv'))

CodePudding user response:

I could be wrong, but I think you wanted unique IDs, so I changed the name dataset.

Using purrr package, you can iterate over the entire list and create a CSV file for each ID.

name <- paste0("ID", 1:3) # Changed this to have unique IDs
city <- c("London", "Paris", "Tokio")

my_df <- data.frame(name = name, city = city)

my_df %>%
  split(name) %>%
  purrr::iwalk(~ readr::write_csv(.x, paste0("~/Desktop/", .y, ".csv")))

  • Related