Ben
Ben

Reputation: 21625

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

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?

Upvotes: 8

Views: 7093

Answers (2)

Seyma Kalay
Seyma Kalay

Reputation: 2859

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

Upvotes: 1

Julius Vainora
Julius Vainora

Reputation: 48201

Here is an approach with base R only:

lapply(mylist, transform, ratio = y / y[1])
# [[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

It might be easier to understand when written as

lapply(mylist, function(x) transform(x, ratio = y / y[1]))

Also, see ?transform.

Upvotes: 15

Related Questions