I am using write.csv()
in R to create many csv files from dataframes. I am currently manually naming the csv file each time. Is there a way to use the values in specific columns in the dataframe to name the file in write.csv()
?
For example, here is a part of the dataframe:
Date | Time | Camera |
---|---|---|
2022-06-13 | 05_26_15 | 1 |
2022-06-13 | 06_26_20 | 1 |
2022-06-13 | 07_26_20 | 1 |
2022-06-13 | 08_26_21 | 1 |
I want to name the file with the value for the "Date" column and the "Camera" column. Something like this:
write.csv(df, "Camera_01_2022_06_13.csv")
I've tried using some of the same syntax as I use to read in files with specific names (via pattern = ) but haven't had any luck.
Thanks for any tips!
CodePudding user response:
Try something like this, and fine tune to your own needs:
library(stringr)
df <- structure(list(Date = c("2022-06-13", "2022-06-13", "2022-06-13"
), Time = c("05_26_15", "06_26_20", "07_26_20"), Camera = c(1L,
1L, 1L)), class = "data.frame", row.names = c(NA, -3L))
file_name <- str_c("Camera", df$Camera[1], df$Date[1], sep = "_") %>%
str_replace_all("[:punct:]", "_") %>%
str_c(".csv")
#"Camera_1_2022_06_13.csv"
CodePudding user response:
You can use paste
the different parts together including a column name. I add a second paste0
statement in order to add the .csv
to the end of the filename. We can use sprintf
to add a leading 0.
write.csv(df, paste0(paste(
names(df[3]), sprintf("d", df$Camera[1]), gsub("[-]", "_", df$Date[1]), sep = "_"
), ".csv"))
# [1] "Camera_01_2022_06_13.csv"
Data
df <- structure(list(Date = c("2022-06-13", "2022-06-13", "2022-06-13",
"2022-06-13"), Time = c("05_26_15", "06_26_20", "07_26_20", "08_26_21"
), Camera = c(1L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA,
-4L))