我有數據集dplyr操縱橫行分組發生變異
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
的Postcode
和Longitude
。 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
@akrun我編輯了它。謝謝你的提示 –
如果你不修正,它會被關閉:Data.frame中的錯誤(Postcode = c(0,1,2,3,4,5,6),Latitude = c(3.1,: 參數意味着行數不同:7,6 – hrbrmstr