2016-04-28 30 views
1

我有一個如下所示的數據框。如何在R數據幀中執行行數明細比較

SampleDF <- structure(list(FirstVal = c(100, 230, 450, 600), SecondVal = c(566, 
547, 557, 250), ThirdVal = c(782, 479, 823, 178), LowerLimit = c(10, 
15, 22, 50), UpperLimit = c(600, 500, 600, 500)), .Names = c("FirstVal", 
"SecondVal", "ThirdVal", "LowerLimit", "UpperLimit"), row.names = c(NA, 
4L), class = "data.frame") 

我曾經和一個名爲FirstVal, SecondVal and ThirdVal列中的兩個計算列UpperLimit and LowerLimit

我試圖從每行中選取元素,這些元素落在下限和上限內,並丟棄超出UpperLimit的任何元素。消除後,我想找出哪些元素是其餘的最大的,並將其添加到一個新的列。

此外,我希望與它一起添加列名稱。我嘗試通過轉置我的原始數據框來完成此操作,但我在引用原始列時遇到了問題。

如何在R中執行行對比比較?


預期輸出:

SampleDFNew 
    FirstVal SecondVal ThirdVal LowerLimit UpperLimit MaxValBelowUpperLim ColumnName 
1  100  566  782   10  600     566 SecondVal 
2  230  547  479   15  500     479 ThirdVal 
3  450  557  823   22  600     557 SecondVal 
4  600  250  178   50  500     250 SecondVal 

回答

1

這工作!

1.首先找出不屬於限值的值並將其刪除。

2.找到其中最多的元素,並從姓名中提取姓名。

x<-sapply(SampleDF[,1:3],function(x) ifelse(x > SampleDF$LowerLimit & x < SampleDF$UpperLimit,x,NA)) 

SampleDf$Columnname <- colnames(x)[apply(x,1,which.max)] 
+0

爲什麼給下面的錯誤,如果我嘗試使用的功能(有光澤的反應或簡單的函數)內的上述過程? 'colnames(x_r)中的錯誤[apply(x_r,1,which.max)]:無效的下標類型'list'' – sunitprasad1

2

你可以試試:

tmp<-(SampleDF[,1:3]>=SampleDF$LowerLimit & SampleDF[,1:3]<=SampleDF$UpperLimit)*as.matrix(SampleDF[,1:3]) 
colnames(SampleDF[,1:3])[max.col(tmp*NA^(rowSums(tmp)==0))] 
#[1] "SecondVal" "ThirdVal" "SecondVal" "SecondVal" 
+0

完美!但@koundy首先發布它,所以我「接受」了這個答案。 – sunitprasad1

+2

沒問題,很高興它有幫助。還要考慮我的解決方案是矢量化的,應該快得多。 – nicola

+0

是的,它的速度更快。 – sunitprasad1