【发布时间】:2017-05-14 09:34:54
【问题描述】:
我有数据集
x <- data.frame(Postcode = c(1, 2, 3, 4, 5, 6),
Latitude = c(3.1, 3.2, 3.3, 3.3, 3.4, 3.4),
Longitude = c(100, 101, 102, 102, 103, 104),
Exposure = c(1, 2, 3, 4, 5, 6))
我正在尝试操作 x 内部的数据变为
x <- data.frame(Postcode = c(1, 2, 3, 4, 5, 6),
Latitude = c(3.1, 3.2, 3.3, 3.3, 3.4, 3.4),
Longitude = c(100, 101, 102, 102, 103, 104),
Exposure = c(1, 2, 3, 4, 5, 6),
coords = c("3.1, 100", "3.2, 101", "3.3, 102", "3.3, 102",
"3.4, 103", "3.4, 104"),
postcode = c("1", "2", "3,4", "3,4", "5", "6"),
exposure = c(1, 2, 7, 7, 5, 6))
新列postcode 会将具有相同Latitude 和Longitude 的Postcode 粘贴在一起。 coords 将粘贴Latitude 和Longitude,而exposure 将求和具有相同coords 的Exposure,即相同的Latitude 和Longitude。
我可以通过使用dplyr 包和for 循环来完成此操作
x <- mutate(x, coords = paste(Latitude, Longitude, sep = ", "))
x <- cbind(x, postcode = rep(0, nrow(x)), exposure = rep(0, nrow(x)))
for(i in unique(x$coords)){
x$postcode[x$coords == i] <- paste(x$Postcode[x$coords == i], collapse = ", ")
x$exposure[x$coords == i] <- sum(x$Exposure[x$coords == i])
}
我怎样才能通过仅使用 dplyr 包而不使用 for 循环来完成此操作?或者可能比使用for 循环更有效的其他方法,因为我的实际数据集非常大
【问题讨论】:
-
第二个数据集的元素数量不相等。请更新它
-
@akrun 我已经编辑过了。感谢您的通知
-
如果不修复就会关闭:Data.frame 中的错误(Postcode = c(0, 1, 2, 3, 4, 5, 6), Latitude = c(3.1 , : 参数暗示不同的行数:7, 6
-
@hrbrmstr 抱歉,我已经修复了