Samet Sökel
Samet Sökel

Reputation: 2670

How to paste two list columns with the same order?

I have a data.frame which has two list typed column like this;

df <- data.frame(arbitrary=matrix(data = 1:3,nrow = 3))

column_numeric <- list(list(1,2,3),list(4,5,6),list(7,8,9))

column_char <- list(list('A','B','C'),list('B','C','D'),list('D','G','J'))

df$column_numeric <- column_numeric
df$column_char <- column_char
df$arbitrary <- NULL

df 

  column_numeric column_char
1        1, 2, 3     A, B, C
2        4, 5, 6     B, C, D
3        7, 8, 9     D, G, J

I need to paste each element of each list with the same order, I mean the desired output should look so;

  column_numeric column_char desired_column 
  <list>         <list>      <chr>          
1 <list [3]>     <list [3]>  1*A + 2*B + 3*C
2 <list [3]>     <list [3]>  4*B + 5*C + 6*D
3 <list [3]>     <list [3]>  7*D + 8*G + 9*J

base functions would be much better.

Thanks in advance.

Upvotes: 1

Views: 93

Answers (1)

caldwellst
caldwellst

Reputation: 5956

You can use mapply to iterate over each list. We can paste the vectors together with sep = "*" to get the multiples and collapse = " + ".

df$desired_column <- mapply(
  paste,
  df$column_numeric,
  df$column_char,
  sep = "*",
  collapse = " + "
)

df
#>   column_numeric column_char  desired_column
#> 1        1, 2, 3     A, B, C 1*A + 2*B + 3*C
#> 2        4, 5, 6     B, C, D 4*B + 5*C + 6*D
#> 3        7, 8, 9     D, G, J 7*D + 8*G + 9*J

Upvotes: 4

Related Questions