我有這個資料集(104x182),對于每一列,我想找到該列中最大值的行索引。
這是我到目前為止所擁有的:
library(tibble)
p=1:182
DF <- tibble(i=as.numeric(), max=as.numeric())
for (i in p){
max <- which.max(Z0[, p])
DF <- DF %>%
add_row(i=i, max=max)
}
DF %>%
filter(max != 1) %>%
distinct(max, .keep_all=TRUE)
當我嘗試運行 for 回圈時,出現以下錯誤:
Error in which.max(Z0[, p]) :
'list' object cannot be coerced to type 'double'
如何更改上述代碼以使其正常作業。
uj5u.com熱心網友回復:
如果您正在尋找每列中最大值的索引,我認為這就是您要尋找的:
set.seed(123)
#test data
df<- as.data.frame(matrix(as.integer(runif(200, 0, 100)), ncol=10))
#row index of max value in each column
answer <- apply(df, MARGIN = 2, which.max)
answer
# V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
# 11 4 19 5 7 4 6 5 19 13
uj5u.com熱心網友回復:
我們可以max.col使用base R
max.col(t(df1), "first")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/522839.html
標籤:r数据框for循环小标题
上一篇:對資料框的每3列求和以形成新列
