jormaga
jormaga

Reputation: 311

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!

Upvotes: 4

Views: 2626

Answers (3)

akrun
akrun

Reputation: 887223

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

Upvotes: 4

utubun
utubun

Reputation: 4520

You've just missed the SIMPLIFY = FALSE in your mapply() call:

dplyr::mutate(IDs, togeher = mapply(c, V1, V2, SIMPLIFY = F))

  V1 V2 togeher
1  1  6    1, 6
2  1  8    1, 8
3  6  8    6, 8

Upvotes: 3

Paweł Chabros
Paweł Chabros

Reputation: 2399

You can do it with purrr's map2 function:

library(dplyr)
library(purrr)

IDs %>% 
  mutate(together = map2(V1, V2, ~c(.x, .y)))

Upvotes: 7

Related Questions