MAP
MAP

Reputation: 39

Creating variable in multiple dataframes with different number with R

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

Answers (3)

randr
randr

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.frames 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

akrun
akrun

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

Sweepy Dodo
Sweepy Dodo

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

Related Questions