R function to create data.frame based on variable in a column
I'm new to R and having some trouble. If I have a df call 'xyz' as below.
C1 | C2 | C3 |
---|---|---|
x | 1 | Three |
x | 2 | Three |
y | 1 | Three |
y | 0 | Three |
z | 2 | Three |
z | 1 | Three |
from the df above, I want to crate separate data frames named with variables in c1 such as:
data frame name 'x'
C1 | C2 | C3 |
---|---|---|
x | 1 | Three |
x | 2 | Three |
data frame name 'y'
C1 | C2 | C3 |
---|---|---|
y | 1 | Three |
y | 0 | Three |
data frame name 'z'
C1 | C2 | C3 |
---|---|---|
z | 2 | Three |
z | 1 | Three |
sorry if it is already answered but I couldn't find any good solution for now.
Since you are new to R its ideal to stick to base R. But keeping a dplyr option for future use as well.
df %>%
group_by(`C1`) %>%
group_walk( ~ write_csv(
.x,
paste0(
"path_to_your_folder",
"file_prefix_if_required_",
.y$C1,
".csv"
) #paste0 function willbuild a custom filename as per your needs
), .keep = TRUE) #.keep=T will keep the grouped column in the file.
Pls check help on dplyr::group_walk and it has an example as well.