R在嵌套数据集中添加一列

Mic*_*tta 3 nested r dplyr tidyr purrr

作为更复杂的过程的一部分,我发现自己迷失了这段话。下面是我正在处理的可复制示例。我需要为每个嵌套数据集添加一列,其中具有相同的编号,但它们之间的编号不同。具体来说,数字必须是写入的数字c1$Age。该代码cbind(k, AgeGroup = 3)仅用于演示。实际上,当我使用时cbind(k, AgeGroup = Age),R给我以下错误Error in mutate_impl(.data, dots): Evaluation error: arguments imply differing number of rows: 5, 2.

library(dplyr)
library(purrr)
library(magrittr)
library(tidyr)

c <- read.table(header = TRUE, text = "Age Verbal  Fluid  Speed 
2     89     94    103    
1     98     88    100    
1    127    115    102    
2     83    101     71    
2    102     92     87   
1     91     97    120   
1     96    129     98   
2     79     92     84    
2    107     95    102")

c1 <- c %>% 
  group_by(Age) %>% 
  nest() %>% 
  dplyr::mutate(db = data %>% map(function(k) cbind(k, AgeGroup = 3)))

#> c1
# A tibble: 2 x 3
#    Age data             db                  
#  <int> <list>           <list>              
#1     2 <tibble [5 x 3]> <data.frame [5 x 4]>
#2     1 <tibble [4 x 3]> <data.frame [4 x 4]>
Run Code Online (Sandbox Code Playgroud)

这就是我现在所拥有的:

#> c1$db
#[[1]]
#  Verbal Fluid Speed AgeGroup
#1     89    94   103        3
#2     83   101    71        3
#3    102    92    87        3
#4     79    92    84        3
#5    107    95   102        3
#
#[[2]]
#  Verbal Fluid Speed AgeGroup
#1     98    88   100        3
#2    127   115   102        3
#3     91    97   120        3
#4     96   129    98        3
Run Code Online (Sandbox Code Playgroud)

这就是我想要的。

#> c1$db
#[[1]]
#  Verbal Fluid Speed AgeGroup
#1     89    94   103        2
#2     83   101    71        2
#3    102    92    87        2
#4     79    92    84        2
#5    107    95   102        2
#
#[[2]]
#  Verbal Fluid Speed AgeGroup
#1     98    88   100        1
#2    127   115   102        1
#3     91    97   120        1
#4     96   129    98        1
Run Code Online (Sandbox Code Playgroud)

Jul*_*ora 5

您可以替换为mapmap2并以此方式保持对的相应值的了解Age

c1 <- c %>% group_by(Age) %>% nest() %>% 
  dplyr::mutate(db = data %>% map2(Age, function(k, age) cbind(k, AgeGroup = age)))
c1$db
# [[1]]
#   Verbal Fluid Speed AgeGroup
# 1     89    94   103        2
# 2     83   101    71        2
# 3    102    92    87        2
# 4     79    92    84        2
# 5    107    95   102        2
#
# [[2]]
#   Verbal Fluid Speed AgeGroup
# 1     98    88   100        1
# 2    127   115   102        1
# 3     91    97   120        1
# 4     96   129    98        1
Run Code Online (Sandbox Code Playgroud)

当您cbind(k, AgeGroup = Age)直接尝试时,问题在于那Age是一个vector 2:1,而不是一个相应的值。