【发布时间】:2019-06-28 01:08:50
【问题描述】:
我有一个包含两列(V1 和 V2)的数据框,我想创建另一个向量列 - 通过组合函数:c() - 将其他列作为参数。
我将 dplyr 用于所有任务,所以我也想在这种情况下使用它。
我尝试使用 apply 函数创建新列,但它返回一个包含所有行(不是按行)的向量,这让我感到惊讶,因为它与其他函数一起按行工作。
我已经使用 rowwise 函数解决了这个问题,但由于它通常效率不高,我想看看是否还有其他选择。
这里是数据框的定义:
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
提前致谢!
【问题讨论】: