找到DataFrame的最大行

时间:2011-10-14 08:10:29

标签: r function

这是the question presented for matrix before的变体。

我需要逐行查找数据帧的第一个,第二个......最大值 将每一个存储在一个单独的新列中。

我需要构建的功能应该如下所示:

> set.seed(1)
> v1 <- runif(10,1,10)
> v2 <- runif(10,1,10)
> v3 <- runif(10,1,10)
> Dt <- datal.frame( v1, v2, v3 )
> head(Dt, 3)
     v1    v2    v3
1 3.390 2.854 9.412
2 4.349 2.589 2.909
3 6.155 7.183 6.865
> label <- big(Dt, pos=1)
#### # big a function to find the first, second, .... (pos) biggets value and returns its label
> label
[1] "v3" "v1" "v2" ...
> big(Dt, pos=2)
[1] "v1" "v3" "v3" ...

感谢。 涓

1 个答案:

答案 0 :(得分:2)

正如@Spacedman所说,你应该提供更多细节。因此,无论这个答案是否有用,请尝试重新构建您的问题。

我猜你有一个data.frame / matrix,并且每行要提取第n个最大值。

##Set up some dummy data
R> set.seed(1)
R> v1 <- runif(10,1,10); v2 <- runif(10,1,10)
R> v3 <- runif(10,1,10); Dt <- data.frame( v1, v2, v3 )
R> head(Dt, 2)
     v1    v2    v3
1 3.390 2.854 9.412
2 4.349 2.589 2.909

##Step 1: Use "apply" and "order" to order rows
##Step 2: Use subsetting to extract a particular value
R> big = function(Dt, pos=1) {
+    ordered_rows <- apply(Dt, 1, order, decreasing = TRUE)
+    positions <- rep(colnames(Dt), nrow(Dt))[as.vector(ordered_rows[pos,])]
+    return(positions)
+  }
R> big(Dt, 3)
 [1] "v2" "v2" "v1" "v3" "v1" "v3" "v3" "v3" "v2" "v1"
R> big(Dt, 1)
 [1] "v3" "v1" "v2" "v1" "v2" "v1" "v1" "v2" "v3" "v2"