创建一个新列,它是其他列的向量

jor*_*aga 4 r apply lapply dplyr mutate

我有一个包含两列(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)
                 )
Run Code Online (Sandbox Code Playgroud)

这是列的创建(一起是错误的结果,一起是好的结果):

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()
Run Code Online (Sandbox Code Playgroud)

以下是打印结果:

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
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Paw*_*ros 5

你可以用purrr'smap2函数做到这一点:

library(dplyr)
library(purrr)

IDs %>% 
  mutate(together = map2(V1, V2, ~c(.x, .y)))
Run Code Online (Sandbox Code Playgroud)