我有一个包含一些重复项的数据框.我想对存在重复的两列的行进行求和,然后删除不需要的行.
这是一个数据的例子,
Year ID Lats Longs N n c_id
2015 200 30.5417 -20.5254 150 30 4142
2015 200 30.5417 -20.5254 90 50 4142
Run Code Online (Sandbox Code Playgroud)
我想将N列和n列合并为一行.剩下的信息,即Lats,Longs,ID和Year将保持不变,例如,
Year ID Lats Long N n c_id
2015 200 30.5417 -20.5254 240 80 4142
Run Code Online (Sandbox Code Playgroud)
解决方案data.table:
require(data.table)
df <- structure(list(year = c(2015, 2015), ID = c(200, 200), Lats = c(30.5417,
30.5417), Longs = c(-20.5254, -20.5254), N = c(150, 90), n = c(30,
50), c_id = c(4142, 4142)), .Names = c("year", "ID", "Lats",
"Longs", "N", "n", "c_id"), row.names = c(NA, -2L),
class = "data.frame")
dt <- data.table(df)
dt[, lapply(.SD, sum), by="c_id,year,ID,Lats,Longs"]
c_id year ID Lats Longs N n
1: 4142 2015 200 30.5417 -20.5254 240 80
Run Code Online (Sandbox Code Playgroud)
解决方案plyr:
require(plyr)
ddply(df, .(c_id, year, ID, Lats, Longs), function(x) c(N=sum(x$N), n=sum(x$n)))
c_id year ID Lats Longs N n
1 4142 2015 200 30.5417 -20.5254 240 80
Run Code Online (Sandbox Code Playgroud)