我有一个数据帧数据。我想为每行选择带符号的最大绝对值。
set.seed(10987)
dat = data.frame( V1 = letters[1:5], V2 = rnorm(5), V3 = rnorm(5), V4 =(rnorm(5)))
预期产出
dat
V1 V2 V3 V4 max
a -0.6357365 -0.3928079 -0.5059575 -0.6357365
b -0.4616447 -0.3199929 1.3430388 1.3430388
c 1.4322822 -0.2791133 -0.2145794 1.4322822
d -0.6506964 0.4941883 -0.1795565 -0.6506964
e -0.2073807 -0.1773305 -0.1001907 -0.2073807
答案 0 :(得分:2)
我们可以使用row/column
索引。我们得到每行中绝对最大元素的列索引,其中max.col
,cbind
包含行序列,根据索引提取值,并创建一个新列max
< / p>
dat$max <- dat[-1][cbind(1:nrow(dat), max.col(abs(dat[-1])))]
dat$max
#[1] -0.6357365 1.3430388 1.4322822 -0.6506964 -0.2073807
dat <- structure(list(V1 = c("a", "b", "c", "d", "e"), V2 = c(-0.6357365,
-0.4616447, 1.4322822, -0.6506964, -0.2073807), V3 = c(-0.3928079,
-0.3199929, -0.2791133, 0.4941883, -0.1773305), V4 = c(-0.5059575,
1.3430388, -0.2145794, -0.1795565, -0.1001907)), .Names = c("V1",
"V2", "V3", "V4"), row.names = c(NA, -5L), class = "data.frame")