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!
You can do it with purrr
's map2
function:
library(dplyr)
library(purrr)
IDs %>%
mutate(together = map2(V1, V2, ~c(.x, .y)))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With