我正在寻找过滤数据的最简单方法:
我们以那个为例:
structure(list(mpg = c(21, 21, 22.8, 21.4, 18.7, 18.1, 14.3,
24.4, 22.8, 19.2), cyl = c(6, 6, 4, 6, 8, 6, 8, 4, 4, 6), disp = c(160,
165, 108, 258, 360, 225, 360, 146.7, 140.8, 167.6), hp = c(310,
110, 93, 110, 475, 105, 245, 62, 95, 223), drat = c(3.9, 3.9,
3.85, 3.08, 3.15, 2.76, 633.21, 3.69, 3.92, 3.92), wt = c(2.62,
2.875, 2.32, 3.215, 3.44, 3.46, 3.57, 3.19, 3.15, 3.44), qsec = c(16.46,
17.02, 18.61, 19.44, 17.02, 20.22, 15.84, 20, 22.9, 18.3), vs = c(0,
0, 1, 1, 0, 1, 0, 1, 1, 1), am = c(1, 1, 1, 0, 0, 0, 0, 0, 0,
0), gear = c(4, 4, 4, 3, 3, 3, 3, 4, 4, 4), carb = c(4, 4, 1,
1, 2, 1, 4, 2, 2, 4)), .Names = c("mpg", "cyl", "disp", "hp",
"drat", "wt", "qsec", "vs", "am", "gear", "carb"), row.names = c("Mark_1",
"Mark_2", "Mark_3", "Tom_1", "Tom_2", "Tim_1", "Greg_1", "Greg_2",
"Greg_3", "Greg_4"), class = "data.frame")
我想使用“相同”名称过滤行,并且只保留一行。有些名称仅在_
之后的数字上有所不同。这些应该相互比较。
过滤条件:
我想首先找到每行中的最大值,然后取这些最大值并在具有相同名称的行之间进行比较。应保留具有最高最大值的行
如果我没弄错的话,删除了输出:
structure(list(mpg = c(21, 18.7, 18.1, 14.3), cyl = c(6, 8, 6,
8), disp = c(160, 360, 225, 360), hp = c(310, 475, 105, 245),
drat = c(3.9, 3.15, 2.76, 633.21), wt = c(2.62, 3.44, 3.46,
3.57), qsec = c(16.46, 17.02, 20.22, 15.84), vs = c(0, 0,
1, 0), am = c(1, 0, 0, 0), gear = c(4, 3, 3, 3), carb = c(4,
2, 1, 4)), .Names = c("mpg", "cyl", "disp", "hp", "drat",
"wt", "qsec", "vs", "am", "gear", "carb"), row.names = c("Mark_1",
"Tom_2", "Tim_1", "Greg_1"), class = "data.frame")
> datas
mpg cyl disp hp drat wt qsec vs am gear carb
Mark_1 21.0 6 160 310 3.90 2.62 16.46 0 1 4 4
Tom_2 18.7 8 360 475 3.15 3.44 17.02 0 0 3 2
Tim_1 18.1 6 225 105 2.76 3.46 20.22 1 0 3 1
Greg_1 14.3 8 360 245 633.21 3.57 15.84 0 0 3 4
答案 0 :(得分:3)
我们通过在删除子字符串split
后跟数字list
创建包含行名称的分组变量,将数据集data.frame
_
\\d+
list
}),然后循环遍历pmax
,找到每行的最大值(which.max
),获取最大值的索引(rbind
),使用它来对行进行子集化,以及行do.call(rbind, setNames(lapply(split(df1, sub("_\\d+", "", rownames(df1))),
function(x) x[which.max(do.call(pmax, x)),]), NULL))
# mpg cyl disp hp drat wt qsec vs am gear carb
#Greg_1 14.3 8 360 245 633.21 3.57 15.84 0 0 3 4
#Mark_1 21.0 6 160 310 3.90 2.62 16.46 0 1 4 4
#Tim_1 18.1 6 225 105 2.76 3.46 20.22 1 0 3 1
#Tom_2 18.7 8 360 475 3.15 3.44 17.02 0 0 3 2
ave
或者使用max
,我们创建一个逻辑索引。获取每一行do.call(pmax, df1)
(max
),使用子字符串后的行名作为分组变量,获取==
值,与元素进行比较(df1[with(df1, as.logical(ave(do.call(pmax, df1), sub("_\\d+", "", rownames(df1)),
FUN = function(x) x==max(x)))),]
# mpg cyl disp hp drat wt qsec vs am gear carb
#Mark_1 21.0 6 160 310 3.90 2.62 16.46 0 1 4 4
#Tom_2 18.7 8 360 475 3.15 3.44 17.02 0 0 3 2
#Tim_1 18.1 6 225 105 2.76 3.46 20.22 1 0 3 1
#Greg_1 14.3 8 360 245 633.21 3.57 15.84 0 0 3 4
) ,转换为逻辑和子集行
this.items