How do I add a column to each data frame in a list

Viewed 5773

Here's my setup

df1<-data.frame(time=c(1,2,3),y=c(2,3,6))
df2<-data.frame(time=c(1,2,3),y=c(3,4,7))
mylist<-list(df1,df2)

mylist
[[1]]
  time y
1    1 2
2    2 3
3    3 6

[[2]]
  time y
1    1 3
2    2 4
3    3 7

I would like to add a column, ratio to each dataframe, where it's the ratio of the value of y relative to the y value at time 1. It would be equivalent to doing

mylist[[1]]$ratio<-mylist[[1]]$y/mylist[[1]]$y[1]
mylist[[2]]$ratio<-mylist[[2]]$y/mylist[[2]]$y[1]

mylist
[[1]]
  time y ratio
1    1 2   1.0
2    2 3   1.5
3    3 6   3.0

[[2]]
  time y    ratio
1    1 3 1.000000
2    2 4 1.333333
3    3 7 2.333333

Any suggestions on how to do this?

2 Answers
df  <- data.frame(time=c(1,2,3),y=c(2,3,6))
df2 <- data.frame(time=c(1,2,3),y=c(3,4,7))
mylist <- list(df1,df2)
mylist


for (i in 1:(length(mylist))) {
  mylist[[i]]$ratio <- mylist[[i]]$y/mylist[[i]]$y[1]
}

mylist
Related