Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lapply to Add Columns to Each Dataframe in a List [duplicate]

Tags:

r

my question is two-fold..

  1. I have a list of dataframes, and using lapply in R, I would like to add a column to each dataframe in the list.
  2. The added column should actually take values sequentially from a list, if possible. I have a list that is the same length as the list of dataframes, and each value in that list should be the added column value.

The reason I'm doing this is because the file name of each data set I'm importing has date info, e.g. the file name contains Jun12_2003. So I want to import each data set, and then assign a column for year and date, taking the info from the file name (so far doing that part with regexp).

Thanks for any help!

like image 698
setophaga Avatar asked Apr 07 '14 00:04

setophaga


1 Answers

Use Map. It is short for mapply(..., SIMPLIFY = FALSE) as suggested by Ari.

df1 <- data.frame(x = runif(3), y = runif(3))
df2 <- data.frame(x = runif(3), y = runif(3))
dfs <- list(df1, df2)
years <- list(2013, 2014)

Map(cbind, dfs, year = years)
# [[1]]
#           x         y year
# 1 0.8843945 0.6285246 2013
# 2 0.8400041 0.1369520 2013
# 3 0.4398870 0.4660476 2013
# 
# [[2]]
#           x         y year
# 1 0.4153315 0.5831114 2014
# 2 0.9685105 0.2398060 2014
# 3 0.9507591 0.7585670 2014
like image 56
flodel Avatar answered Nov 14 '22 01:11

flodel