Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new column which is a vector of other columns

I have a dataframe with two columns (V1 and V2) and I'd like to create another column which is a vector - via combine function: c() - taking as arguments the other columns.

I'm using dplyr for all tasks, so I'd like to use it also in this context.

I've tried to create the new column with an apply function but it returns a vector with all the rows (not rowwise), something which surprises me, because with other functions it works rowwise.

I've solved it using the function rowwise, but as it's not usually so efficient, I'd like to see if there's another option.

Here is the definition of the dataframe:

IDs <- structure(list(V1 = c("1", "1", "6"),
                      V2 = c("6", "8", "8")),
                 class = "data.frame",
                 row.names = c(NA, -3L)
                 )

Here is the creation of the columns (together1 is the wrong result, and together2 the good one):

IDs <-
  IDs %>% 
  mutate(together1 = list(mapply(function (x,y) c(x,y), V1, V2))
        ) %>%
  rowwise() %>% 
  mutate(together2 = list(mapply(function (x,y) c(x,y), V1, V2))
        ) %>% 
  ungroup()

Here are the printed results:

print(as.data.frame(IDs))

V1 V2        together1 together2
1  1  6 1, 6, 1, 8, 6, 8      1, 6
2  1  8 1, 6, 1, 8, 6, 8      1, 8
3  6  8 1, 6, 1, 8, 6, 8      6, 8

Thanks in advance!

like image 435
jormaga Avatar asked Dec 14 '22 13:12

jormaga


2 Answers

You can do it with purrr's map2 function:

library(dplyr)
library(purrr)

IDs %>% 
  mutate(together = map2(V1, V2, ~c(.x, .y)))
like image 64
Paweł Chabros Avatar answered Mar 03 '23 22:03

Paweł Chabros


pmap could be used here

library(tidyverse)
IDs %>% 
   mutate(together = pmap(unname(.), c)) 
#  V1 V2 together
#1  1  6     1, 6
#2  1  8     1, 8
#3  6  8     6, 8
like image 38
akrun Avatar answered Mar 03 '23 22:03

akrun