2016-06-29 72 views
1

以下是一個示例數據框。搜索R數據框中所有列的值

df = data.frame(company = c('a', 'b', 'c', 'd'), 
       bond = c(0.2, 1, 0.3, 0), 
       equity = c(0.7, 0, 0.5, 1), 
       cash = c(0.1, 0, 0.2, 0)) 
df 

    company bond equity cash 
1  a 0.2 0.7 0.1 
2  b 1.0 0.0 0.0 
3  c 0.3 0.5 0.2 
4  d 0.0 1.0 0.0 

我需要找到在任何列中都有1.0的公司。 預期結果應該是b和d

請提供適用於> 20列的解決方案。 像df %>% filter(bond == 1)這樣的解決方案僅適用於搜索特定列。

dplyrdata.table解決方案是可以接受的。

謝謝。

+0

檢查平等與花車是一個容易出錯的業務,fyi。嘗試查看'x =(.1 + .2)*(10/3)',然後測試'x == 1' ... – Frank

+0

Fwiw,這裏有一些關於這個問題的變化:http://stackoverflow.com/q/28233561 /和http://stackoverflow.com/q/25692392/ – Frank

回答

4

使用rowSums檢查邏輯數據幀應該工作:

df[rowSums(df[-1] == 1.0) != 0, 'company'] 
[1] b d 
Levels: a b c d 
+0

順便說一句,就在一旁......你可以分享你將如何搜索非數字列? – shawnl

+0

您的意思是每個色譜柱的過濾條件不同?我不認爲這種方法適用於這種情況。無論如何,你需要更具體地瞭解欄目和條件。 – Psidom

1
var <- df %>% select(bond:cash) %>% names 
plyr::ldply(var, function(x) paste("filter(df,", x, "==1)") %>% parse(text=.) %>% eval) 
    company bond equity cash 
1  b 1  0 0 
2  d 0  1 0 
4

另一種選擇:

df[unique(row(df[-1])[df[-1] == 1L]),] 
# company bond equity cash 
#2  b 1  0 0 
#4  d 0  1 0 

df$company[unique(row(df[-1])[df[-1] == 1L])] 
#[1] b d 
#Levels: a b c d 
+0

這個工作嗎? 'df [row(df)[df == 1],]' –

+1

@PierreLafortune - 在這種情況下,是的,但我認爲如果多列中有1個,則需要唯一。 – thelatemail

4

我們還可以用Reduce==

res <- df[Reduce(`+`, lapply(df[-1], `==`, 1))!=0,] 
res 
# company bond equity cash 
#2  b 1  0 0 
#4  d 0  1 0 

res$company 
#[1] b d 
#Levels: a b c d 
+2

我覺得akrun的方式是'df [!! rowSums(df == 1),]':) –

+0

@PierreLafortune是的,你說得對,但有人已經用'rowSums'發佈瞭解決方案,所以我不想進入一場關於剽竊的爭論:-) – akrun

+1

他們把'x!= 0'部分弄錯了 –

相關問題