I have these two dataframes:
df1 <-data.frame(v1=c("a","b"),v2=c("c","d"))
df2 <-data.frame(v1=c("a","b"),v2=c("c","d"))
I want to do a loop that creates a new variable (v3) that concatenates variables v1 and v2 for each dataframe, something like this:
for (i in 1:2) {
df[[i]]$v3 <- paste(a[[i]]$v1,a[[i]]$v2)
}
Thus, the final dataframe df1 would be:
v1 | v2 | v3 |
---|---|---|
a | c | ac |
b | d | bd |
And for df2 would be:
v1 | v2 | v3 |
---|---|---|
a | c | ac |
b | d | bd |
CodePudding user response:
Here, we need assign
to update the original objects
for(obj in c("df1", "df2")) {
tmp <- get(obj)
tmp$v3 <- paste0(tmp$v1, tmp$v2)
assign(obj, tmp)
}
-output
> df1
v1 v2 v3
1 a c ac
2 b d bd
> df2
v1 v2 v3
1 a c ac
2 b d bd
Or instead of creating/updating multiple objects, it may be done in a list
lst1 <- lapply(mget(ls(pattern = "^df\\d $")),
transform, v3 = paste0(v1, v2))
If needed to update the original objects, use list2env
list2env(lst1, .GlobalEnv)
CodePudding user response:
library(data.table)
lapply(c('df', 'df_1'), \(i) setDT(get(i)))
lapply(c('df', 'df_1'), \(i) get(i)[, v3 := paste0(v1,v2)])