将列中的值添加或附加到数据框中另一列中的列表

add or append a value in a column to the list in another column in data frame

这是一个示例数据框

library(tidyverse)
library(purrr)
df <- data_frame(abc = letters[1:3], 
                 lst = list(1:3, 1:3, 1:3), 
                 new_data=1:3)

这将给出结果输出

# A tibble: 3 x 3
    abc       lst new_data
  <chr>    <list>    <int>
1     a <int [3]>        1
2     b <int [3]>        2
3     c <int [3]>        3

我想将 new_data 列中的数字附加到 lst 列表列中的相应列表。

这是我到目前为止得到的数量:

df %>%
  mutate(lst= map(lst, ~ append(.,new_data)))

结果是

# A tibble: 3 x 3
    abc       lst new_data
  <chr>    <list>    <int>
1     a <int [6]>        1
2     b <int [6]>        2
3     c <int [6]>        3

我原本希望第一个列表有 1,2,3,1,第二个列表有 1,2,3,2,但它们都是 1,2,3,1,2,3。在 mutate 行中,mutate(lst= map(lst, ~ append(.,new_data)))lst 被视为每行的单个项目,但有些 new_data 被视为整列,而不是行中的相应值。

如何只添加一个值?

您需要 purrr::pmap,它的功能类似于 "zipper"(类似于 R 的基数 mapply 和 python 的 zip) .

df %>%
  mutate(lst = pmap(list(lst, new_data), ~ append(..1, ..2))) %>%
  str()
# Classes 'tbl_df', 'tbl' and 'data.frame': 3 obs. of  3 variables:
#  $ abc     : chr  "a" "b" "c"
#  $ lst     :List of 3
#   ..$ : int  1 2 3 1
#   ..$ : int  1 2 3 2
#   ..$ : int  1 2 3 3
#  $ new_data: int  1 2 3

根据 thelatemail 的建议,您不需要 append 此处:

df %>%
  mutate(lst = pmap(list(lst, new_data), c))