[英]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
list-column中的相應列表。
這是到目前為止我得到了多少:
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
,其功能類似於某種“拉鏈”(類似於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
如最新郵件所述,您無需在此處append
:
df %>%
mutate(lst = pmap(list(lst, new_data), c))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.