Dries Dries - 27 days ago 8
R Question

R - list of identically named data frames: select on variable name

I have a list of data frames with the same structure (same variable-names, same number of observations). Something like

df1<-data.frame(a=c(1,2),condition=c(TRUE,FALSE))
df2<-data.frame(a=c(1,2),condition=c(TRUE,TRUE))

df.list<-list(df1,df2)


And I want to automate (mainly make the code independent of the number dataframes in the list) things like

DF$Condition = df.list[[1]]$Condition + df.list[[2]]$Condition


or

DF$Condition = all(df.list[[1]]$Condition, df.list[[2]]$Condition )

Answer

We can use Reduce with + after subsetting the 'condition' column

Reduce(`+`, lapply(df.list, `[`, 'condition'))

and for the second case

Reduce(function(...) identical(...), lapply(df.list, `[`, 'condition'))