gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:04:39 24 4
gpt4 key购买 nike

作为更复杂程序的一部分,我发现自己迷失在这段话中。下面是我正在处理的可重复示例。我需要向每个嵌套数据集添加一列,其中的数字相同,但它们之间的数字不同。具体来说,该数字必须是 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]>

这就是我现在所拥有的:
#> 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

这就是我想要得到的。
#> 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

最佳答案

您可以替换 map来自 map2并以此方式维护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

当您尝试时 cbind(k, AgeGroup = Age)直接,问题是 Age是一个向量 2:1 ,而不是单个对应的值。

关于R 在嵌套数据集中添加一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53642589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com