0

I have a data frame that has two columns, a and b, that either contain single character values or a vector of values in specific rows. I want to combine the two columns so that I can concatanate the values of both the columns in a single vector. However, when i use the pastefunction, I am unable to concatanate the values in each row in a single vector. The following is a reproducible example of this problem:

library(tibble)
library(tidyverse)
data_frame <-
  tribble(
    ~a,              ~b,
    50,              3,
    17,              50,
    c("21", "19"),   50,
    c("1", "10"),    c("50", "51")
  )

data_frame %>% 
  mutate(new_column = paste(a, b))
#> # A tibble: 4 x 3
#>   a         b         new_column                          
#>   <list>    <list>    <chr>                               
#> 1 <dbl [1]> <dbl [1]> "50 3"                              
#> 2 <dbl [1]> <dbl [1]> "17 50"                             
#> 3 <chr [2]> <dbl [1]> "c(\"21\", \"19\") 50"              
#> 4 <chr [2]> <chr [2]> "c(\"1\", \"10\") c(\"50\", \"51\")"

In the new_column column, I want the results to be as following:

c("50" "3")
c("17" "50")
c("21" "19" "50")
c("1" "10" "50" "51") 

Is there a way that I can combine the columns a and b to get the result in the above format? Thank you.

mhovd
  • 3,724
  • 2
  • 21
  • 47
Usman Khaliq
  • 363
  • 3
  • 22

1 Answers1

0

To combine two columns you can use c. In base R, you can do this with Map :

data_frame$new_col <- Map(c, data_frame$a, data_frame$b)

Or in tidyverse use map2 :

library(dplyr)
library(purrr)

data_frame %>% mutate(new_col = map2(a, b, c))

# A tibble: 4 x 3
#  a         b         new_col  
#  <list>    <list>    <list>   
#1 <dbl [1]> <dbl [1]> <dbl [2]>
#2 <dbl [1]> <dbl [1]> <dbl [2]>
#3 <chr [2]> <dbl [1]> <chr [3]>
#4 <chr [2]> <chr [2]> <chr [4]>
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • thanks. also can i do this for multiple columns? as in if I have 4 columns that I want to concatanate, can i run a single map2 function for concatanating all the vectors? – Usman Khaliq Aug 03 '20 at 07:44
  • For more than 2 columns use `pmap` : `data_frame %>% mutate(new_col = pmap(list(a, b), c))`. You should include the columns you want to concatenate in `list(..)`. – Ronak Shah Aug 03 '20 at 07:46