我有两个列表:
列表 1:
id name age
1 jake 21
2 ashly 19
45 lana 18
51 james 23
5675 eric 25
list 2(看电视):
id hours
1 1.1
1 3
1 2.5
45 5.6
45 3
51 2
51 1
51 2
这只是一个例子,真正的列表非常大:列表 1 - 5000 个 ID,列表 2/3/4 - 有超过 100 万行(不是唯一 ID)。
我需要为每个列表 2 及以上计算每个 id 的平均值/总和/计数并将值添加到列表 1。 请注意,我需要将计算保存在另一个具有不同行号的列表中。
例子:
list 1:
id name age tv_average
1 jake 21 2.2
2 ashly 19 n/a
45 lana 18 4.3
51 james 23 1.6667
5675 eric 25 n/a
这是我的尝试:
for (i in 1:nrow(list2)) {
p <- subset(list2,list2$id==i)
list2$tv_average[i==list2$id] <- sum(p$hours)/(nrow(p))
}
错误: 在 22999 行中,它仅适用于 21713 行。
最佳答案
试试这个
#Sample Data
data1 = structure(list(id = c(1L, 2L, 45L, 51L, 5675L), name = structure(c(3L,
1L, 5L, 4L, 2L), .Label = c("ashly", "eric", "jake", "james",
"lana"), class = "factor"), age = c(21L, 19L, 18L, 23L, 25L)
), .Names = c("id",
"name", "age"), row.names = c(NA, -5L), class = "data.frame")
data2 = structure(list(id = c(1L, 1L, 1L, 3L, 45L, 45L, 51L, 51L, 51L,
53L), hours = c(1.1, 3, 2.5, 10, 5.6, 3, 2, 1, 2, 6)), .Names = c("id",
"hours"), class = "data.frame", row.names = c(NA, -10L))
# Use aggregate to calculate Average, Sum, and Count and Merge
merge(x = data1,
y = aggregate(hours~id, data2, function(x)
c(mean = mean(x),
sum = sum(x),
count = length(x))),
by = "id",
all.x = TRUE)
# id name age hours.mean hours.sum hours.count
#1 1 jake 21 2.200000 6.600000 3.000000
#2 2 ashly 19 NA NA NA
#3 45 lana 18 4.300000 8.600000 2.000000
#4 51 james 23 1.666667 5.000000 3.000000
#5 5675 eric 25 NA NA NA
https://stackoverflow.com/questions/41289393/
相关文章:
r - 如何在 R 中获取面板数据固定效应回归的 corr(u_i, Xb)
elixir - 编译 riak_core 项目时,Mix 在 deps.compile 上挂起
apache-spark - 从 spark RDD 中删除空字符串
scala - 如何递归获取 Scala map 中包含的每个列表的最后一个元素?
security - Webpack 样式加载器 appendChild 对 CSP 不友好
spring - 如何设置 Google Cloud 以使用 AngularJS 客户端和 Java