user2814482
user2814482

Reputation: 651

how to add a new column to each dataset in a list

I have looked at some similar questions but they haven't really helped.

I have a list with 4 datasframes and I would like to add a column to each of the 4 dataframes.

below are a few of the commands that I've tried. they all just result in a list of 4 vectors (just the diversity).

abundance_tables<-lapply(abundance_tables,function(tab) tab$diversity<-diversity(tab) )
abundance_tables<-mapply(function(tab) tab$diversity<-diversity(tab),abundance_tables,SIMPLIFY = F )

any help is appreciated.

thanks

Upvotes: 0

Views: 38

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50728

You don't provide sample data, so I'm generating a sample list of 4 data.frames.

lst <- lapply(1:4, function(x) data.frame(one = LETTERS[1:4], two = 1:4))

We add a third column to every data.frame in the list.

lapply(lst, function(x) { x$three = letters[11:14]; x })
#[[1]]
#  one two three
#1   A   1     k
#2   B   2     l
#3   C   3     m
#4   D   4     n
#
#[[2]]
#  one two three
#1   A   1     k
#2   B   2     l
#3   C   3     m
#4   D   4     n
#
#[[3]]
#  one two three
#1   A   1     k
#2   B   2     l
#3   C   3     m
#4   D   4     n
#
#[[4]]
#  one two three
#1   A   1     k
#2   B   2     l
#3   C   3     m
#4   D   4     n

Note that we need to return x, to get the data.frame with the added column.

Upvotes: 2

Related Questions