I am a beginner to coding in R. I have 60 unique ID's in a column with each unique ID having 30 entries, I would like to write a code which automatically creates separate files for each unique ID. This code worked for a single ID
unique(src$ID)
ID2<- subset(src, ID=='099857')
write.csv(pat2,file= "D:/R/ID2.csv")
when I try to loop it using the following code.
for (i in 1:length(unique(src$ID)))
{ unique(src$ID)
id<- subset(src, ID== "i")
paste(id)
write.csv(i,file="D:R/i.csv")
}
I get a file that just counts all the unique IDs (60) and pastes them into an excel sheet.
trying to incorporate the structure for a single ID into an automated loop.
Does anybody have any suggestions? Thank you.
You are iterating over a numeric vector (1:length(unique(src$ID)), but in the loop you refer to i as a character vector "i". Try changing it to:
for(i in unique(src$ID)) {
ID2 <- subset(src, ID == i)
write.csv(ID2, file = paste0("D:/R/",i,".csv"))
}
...if the name of the column that contains the ID is "SampleID," then you should change it to:
for(i in unique(src$SampleID)) {
ID2 <- subset(src, SampleID == i)
write.csv(ID2, file = paste0("D:/R/",i,".csv"))
}