簡體   English   中英

僅從 data.frame 中的某些選定列返回包含最大值的列的名稱

[英]Return name of column containing max value, from only certain selected columns in a data.frame

我想獲取(在 data.table 的新列中)包含 data.frame 中僅幾列中的最大值的列的列名。

這是一個示例 data.frame

# creating the vectors then the data frame ------
id = c("a", "b", "c", "d")
 ignore = c(1000,1000, 1000, 1000) 
 s1 = c(0,0,0,100)
s2 = c(100,0,0,0)
s3 = c(0,0,50,0)
s4 = c(50,0,50,0)
 df1 <- data.frame(id,ignore,s1,s2,s3,s4)  

(1) 現在我想從 s1-s4 列中找到每行中最大數字的列名。 (即忽略名為“忽略”的列)

(2) 如果最大值並列,我希望返回最后一個(例如 s4)列名。

(3) 作為一個額外的好處 - 如果都是 0,我希望 NA 返回

這是我迄今為止最好的嘗試

df2 <- cbind(df1,do.call(rbind,apply(df1,1,function(x) {data.frame(max.col.name=names(df1)[which.max(x)],stringsAsFactors=FALSE)})))

這在每種情況下都會返回忽略,並且(b 行除外)如果我刪除此列並將 s1-s4 列重新排序為 s4-s1 則有效。

你會如何處理這個問題?

確實非常感謝。

我們使用grep為以“s”開頭、后跟數字 (“i1”) 的列創建列索引。 要獲取具有最大值的子集數據集 ('df1[i1]') 的行索引,我們可以使用max.col和選項ties.method='last' 要將只有 0 個值的行轉換為 NA,我們得到rowSums ,檢查它是否為 0 ( ==0 ) 並將它們轉換為NA ( NA^ ) 並乘以max.col輸出。 這可用於提取子集數據集的列名。

i1 <- grep('^s\\d+', names(df1))
names(df1)[i1][max.col(df1[i1], 'last')*NA^(rowSums(df1[i1])==0)]
#[1] "s2" NA   "s4" "s1"
library(dplyr)
library(tidyr)

df1 = data_frame(
  id = c("a", "b", "c", "d")
  ignore = c(1000,1000, 1000, 1000) 
  s1 = c(0,0,0,100)
  s2 = c(100,0,0,0)
  s3 = c(0,0,50,0)
  s4 = c(50,0,50,0))

result = 
  df1 %>%
  gather(variable, value, -id, -ignore) %>%
  group_by(id) %>%
  slice(value %>%
          {. == max(.)} %>%
          which %>%
          last) %>%
  ungroup %>%
  mutate(variable_fix = ifelse(value == 0,
                               NA,
                               variable))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM