简体   繁体   English

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

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

Here's an example 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)

which will give the resulting output 这将给出结果输出

# 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

I would like to append the numbers in new_data column to corresponding list in lst list-column. 我想将new_data列中的数字附加到lst list-column中的相应列表。

This is how much I got so far: 这是到目前为止我得到了多少:

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

and the result is 结果是

# 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

I was expecting to have the first list to have 1,2,3,1 and second list to have 1,2,3,2 but both of them are 1,2,3,1,2,3 . 我期望第一个列表具有1,2,3,1 ,第二个列表具有1,2,3,2但它们都是1,2,3,1,2,3 In the mutate line, mutate(lst= map(lst, ~ append(.,new_data))) , lst is treated as a single item per row but some how new_data is treated as whole column, instead of corresponding value in row. mutate行中, mutate(lst= map(lst, ~ append(.,new_data)))lst被视为每行单个项目,但有些将new_data视为整列,而不是行中的对应值。

How can I add just single value? 如何仅添加单个值?

You need purrr::pmap , which operates its function as a "zipper" of sorts (similar to R's base mapply and python's zip ). 您需要purrr::pmap ,其功能类似于某种“拉链”(类似于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

As suggested by thelatemail, you don't need append here: 如最新邮件所述,您无需在此处append

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM