1
votes

This Issue is almost what I wanted to do, except by the fact of an output being giving as a list of data frames. Let's reproduce the example of mentioned SE issue above.

Let's say I have 2 data frames:

df1
ID col1 col2
x  0     10
y  10    20
z  20    30

df1
ID col1 col2
a  0     10
b  10    20
c  20    30

What I want is an 4th column with an ifelse result. My rationale is:

if col1>=20 in any data.frame I could have named with the pattern "df", then the new column res=1, else res=0.

But I want to create a new column in each data.frame with the same name pattern, not put all of those data.frames in a list and apply the function, except if I could "extract" each 3rd dimension of this list back to individual data frames.

Thanks

1
Do you mean you want the objects df1 and df2 [I'm assuming the duplicate name in your example is a typo] in your workspace to have the new columns, but you want a one-liner instead of writing df1$...=... and df2$...=...?Philip

1 Answers

3
votes

Per @Frank...if my understanding of what you are looking for is correct, consider using data.table. MWE:

library(data.table); 
addcol <- function(x) x[,res:=ifelse(col1>=20,1,0)]
df1 <- data.table(ID=c("x","y","z"),col1=c(0,10,20),col2=c(10,20,30))
df2 <- data.table(ID=c("x","y","z"),col1=c(20,10,20),col2=c(10,20,30))
#modified df2 so you can see different effects
lapply(list(df1,df2),addcol) 

> df1
   ID col1 col2 res
1:  x    0   10   0
2:  y   10   20   0
3:  z   20   30   1

> df2
   ID col1 col2 res
1:  x   20   10   1
2:  y   10   20   0
3:  z   20   30   1

This works because data.table operates by reference on tables, so inside the function you're actually updating the underlying table, not only the scoped reference to the table.