[英]Find the maximum in a row of a DataFrame
這是之前為矩陣提出的問題的變體 。
我需要逐行查找數據幀的第一個,第二個......最大值,並將每個值存儲在一個單獨的新列中。
我需要構建的函數應該如下所示:
> 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" ...
謝謝。 胡安
正如@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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.