我有两列(V1和V2)一个数据帧和我想创建另一列这是一个矢量 - 通过组合函数:C() - 以作为参数的其它列。
我使用dplyr所有的任务,所以我想还可以使用它在这方面。
我试图创建一个应用功能的新列,但它返回的所有行(未横行)的载体,这东西让我惊讶,因为与其他功能的工作原理横行。
我已经使用功能横行解决它,但因为它通常不是那么有效,我想看看是否有另一种选择。
下面是数据框的定义:
IDs <- structure(list(V1 = c("1", "1", "6"),
V2 = c("6", "8", "8")),
class = "data.frame",
row.names = c(NA, -3L)
)
这里是列(together1是错误的结果,并together2好一个)的创建:
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()
下面是打印结果:
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
提前致谢!
你刚刚错过了你的SIMPLIFY = FALSE
调用mapply()
:
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
你可以用purrr
的map2
功能做到这一点:
library(dplyr)
library(purrr)
IDs %>%
mutate(together = map2(V1, V2, ~c(.x, .y)))
pmap
可以在这里使用
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