Reputation: 39
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 |
Upvotes: 2
Views: 296
Reputation: 314
No need for a loop here at all - paste
is vectorised:
df1$v3 <- paste0(df1$v1, df1$v2)
df2$v3 <- paste0(df2$v1, df2$v2)
If you had the data.frame
s in a list, then you could just use a for
loop to append the 3rd column:
l = list(
df1 = data.frame(v1=c("a","b"),v2=c("c","d")),
df2 = data.frame(v1=c("a","b"),v2=c("c","d"))
)
for(i in seq_along(l)){
l[[i]]$v3 <- paste0(l[[i]]$v1, l[[i]]$v2)
}
l
Yields:
$df1
v1 v2 v3
1 a c ac
2 b d bd
$df2
v1 v2 v3
1 a c ac
2 b d bd
Upvotes: 1
Reputation: 887901
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)
Upvotes: 2
Reputation: 1873
library(data.table)
lapply(c('df', 'df_1'), \(i) setDT(get(i)))
lapply(c('df', 'df_1'), \(i) get(i)[, v3 := paste0(v1,v2)])
Upvotes: 0