R中使用的子集行.max

时间:2014-08-20 01:47:04

标签: r

我正在尝试为行的特定子集连续获取最大值。

a <- data.frame(a = rnorm(5), b = rnorm(5), c = rnorm(5), x = rnorm(5), y = rnorm(5), z = rnorm(5))

a
        a           b          c           x           y           z
1 -0.99415010  0.06177776  1.1224987 -0.60239594 -0.53526479  1.26826763
2 -1.17727409 -0.60488488  1.6509299  0.65014481 -0.91940395  0.47520214
3 -0.04944379  1.47238123 -1.1691980  0.07603221 -0.05844166 -0.24809870
4 -0.05230395 -2.52972650 -0.1170329  0.57833492  0.61692175 -0.16939056
5 -0.61666540  0.02606907  0.2438158 -1.01048883 -1.23118019  0.09784697

> names(a)[apply(a, 1, which.max)]
[1] "z" "c" "b" "y" "c"

有没有办法对数据进行子集化,这样我才能得到列x,y和z的which.max结果?当我尝试对我需要的列进行子集化时,我得到了这个错误:

Error in names(---)[apply(----[, 13:68], 1, which.max)] : 
  invalid subscript type 'list'

谢谢!

3 个答案:

答案 0 :(得分:1)

怎么样

 b <- a[,c("x","y","z")]
 names(b)[apply(b, 1, which.max)]

names(a[,4:6])[apply(a[,4:6], 1, which.max)]

答案 1 :(得分:1)

以下情况可能有所帮助(因为您没有使用set.seed,我的&#39; a值与您的不同):

xx = apply(a, 1, which.max)
names(a)[xx[xx>3]]
[1] "y"

如果您只想分析x,y,z列:

> a = a[,4:6]
> names(a)[apply(a, 1, which.max)]
[1] "x" "y" "x" "z" "y"

答案 2 :(得分:0)

您也可以尝试:

   b1 <- a[,letters[24:26]]
    names(b1)[max.col(b1)]
   #[1] "x" "z" "y" "y" "y"

数据

   set.seed(42)
    a <- data.frame(a = rnorm(5), b = rnorm(5), c = rnorm(5), x = rnorm(5), y = rnorm(5), z = rnorm(5))