Reputation: 899
This is a very basic question, but I am struggling to solve it. I have a master data frame that I have split into multiple data frames, based on unique values in a particular column. This was achieved by creating a list of data frames, and then saving each data frame as a separate csv file using the lapply function (see the code below).
Example code:
split_df <- split(df, df$ID)
u_ID <- unique(df$ID)
names(split_df) <- paste(u_ID)
lapply(names(split_df), function(x) write.csv(split_df[x], file= paste0(x, '_ID.csv')))
The issue is that the column headers in the output csv files are different to those in the master data frame i.e. in the example below where the data frame is split by unique ID values, the ID name has been added to each column header in the split data frames. I would like to end up with the same column headers in my output data frames as in my master date frame.
Example data:
ID Count Sp
1 A 23 1
2 A 34 2
3 B 4 2
4 A 4 1
5 C 22 1
6 B 67 1
7 B 51 2
8 A 11 1
9 C 38 1
10 B 59 2
dput:
structure(list(ID = c("A", "A", "B", "A", "C", "B", "B", "A",
"C", "B"), Count = c(23L, 34L, 4L, 4L, 22L, 67L, 51L, 11L, 38L,
59L), Sp = c(1L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L)), .Names = c("ID",
"Count", "Sp"), class = "data.frame", row.names = c(NA, -10L))
Example output data frames (csv files) using above code:
$A
A.ID A.Count A.Sp
1 A 23 1
2 A 34 2
4 A 4 1
8 A 11 1
$B
B.ID B.Count B.Sp
3 B 4 2
6 B 67 1
7 B 51 2
10 B 59 2
$C
C.ID C.Count C.Sp
5 C 22 1
9 C 38 1
For this example, I would like to end up with output csv files containing the column headers ID, Count and Sp. Any solutions would be greatly appreciated!
Upvotes: 0
Views: 1908
Reputation: 12829
Use this simply:
lapply(names(split_df), function(x) write.csv(split_df[[x]], file= paste0(x, '_ID.csv')))
Note double square brackets in split_df[[x]]
.
Upvotes: 2