I'm having trouble making a loop that will iterate through my data and create multiple data frames.
Here's some dummy data:
mydf <- data.frame("color"=c("blue","yellow","red","green","pink","orange","cyan"),
"height"=c(1,2,3,4,5,6,7),
"boy_1"=c(5,1,6,5,5,1,4),
"boy_2"=c(2,2,2,2,2,2,2),
"boy_3"=c(3,3,3,3,3,3,3),
"girl_1"=c(3,3,3,4,4,4,4),
"girl_2"=c(6,6,6,6,6,6,6))
mydf
color height boy_1 boy_2 boy_3 girl_1 girl_2
1 blue 1 5 2 3 3 6
2 yellow 2 1 2 3 3 6
3 red 3 6 2 3 3 6
4 green 4 5 2 3 4 6
5 pink 5 5 2 3 4 6
6 orange 6 1 2 3 4 6
7 cyan 7 4 2 3 4 6
I want to say, "for every column after 'color' and 'height', make a new data frame - keep the 'color' and 'height columns. So in this case, I should return 5 data frames (preferably in a list).
mydf_1 = color, height, boy_1
mydf_2 = color, height, boy_2
...
mydf_5 = color, height, girl_2
I'm new to writing loops like these...This is my attempt (does not work!)
for(i in mydf[,3:ncol(mydf)]{
mylist <- list()
mydf <- i
mylist[[i]] <- mydf #save dataframes to the list?
}
EDIT: Okay I spent some more time and think I got it!
mydf <- data.frame("color"=c("blue","yellow","red","green","pink","orange","cyan"),
"height"=c(1,2,3,4,5,6,7),
"boy_1"=c(5,1,6,5,5,1,4),
"boy_2"=c(2,2,2,2,2,2,2),
"boy_3"=c(3,3,3,3,3,3,3),
"girl_1"=c(3,3,3,4,4,4,4),
"girl_2"=c(6,6,6,6,6,6,6))
mylist <- list()
for(i in seq_along(mydf[,3:ncol(mydf)])){
mylist[[i]] <- mydf[,c(1,2,(i+2))]
}
This seems to return a list with the correct 5 data frames. It took me a while to arrive at the 'i+2' trick.