2009-10-08 94 views
20

我有一個彙總表從data.frame行:如何選擇具有2個條件

> aggdata[1:4,] 
    Group.1 Group.2   x 
1  4 0.05 0.9214660 
2  6 0.05 0.9315789 
3  8 0.05 0.9526316 
4  10 0.05 0.9684211 

我怎樣才能選擇x的值時,我有Group.1和Group.2值?

我想:

aggdata[aggdata[,"Group.1"]==l && aggdata[,"Group.2"]==lamda,"x"] 

但回覆所有X。

更多信息: 我想用這個像這樣:

table = data.frame(); 
for(l in unique(aggdata[,"Group.1"])) { 
    for(lambda in unique(aggdata[,"Group.2"])) { 
     table[l,lambda] = aggdata[aggdata[,"Group.1"]==l & aggdata[,"Group.2"]==lambda,"x"] 
    } 
} 

是更方便,更給這個結果我很欣賞的任何建議!

回答

13

使用&不是& &。後者只評估每個向量的第一個元素。

更新:回答第二部分,使用重塑包。像這樣的事情可以做到這一點:

tablex <- recast(aggdata, Group.1 ~ variable * Group.2, id.var=1:2) 
# Now add useful column and row names 
colnames(tablex) <- gsub("x_","",colnames(tablex)) 
rownames(tablex) <- tablex[,1] 
# Finally remove the redundant first column 
tablex <- tablex[,-1] 

有更多使用重塑經驗的人可能有一個更簡單的解決方案。

注意:不要將table用作變量名稱,因爲它與table()函數衝突。

+0

謝謝!看起來確實選擇了1個元素。但現在,我的循環給出了錯誤:「x [[jj]] < - vjj [FALSE]中的錯誤:嘗試選擇少於一個元素」它仍然不正確? – 2009-10-08 09:20:08

+0

由於當lambda小於1時使用表[l,lambda],所以會生成該錯誤。 – 2009-10-08 09:29:51

+0

我無法弄清楚你試圖做什麼,因爲組元素不是唯一的。 – 2009-10-08 09:33:36

20

最簡單的解決方案是在代碼中將「& &」更改爲「&」。

> aggdata[aggdata[,"Group.1"]==6 & aggdata[,"Group.2"]==0.05,"x"] 
[1] 0.9315789 

我首選的方案是使用子集():

> subset(aggdata, Group.1==6 & Group.2==0.05)$x 
[1] 0.9315789 
+1

爲什麼你更喜歡子集?只是因爲它有點整潔? – naught101 2014-07-14 05:30:03

7

有關於在子集化R數據幀真正有用的文檔: http://www.ats.ucla.edu/stat/r/modules/subsetting.htm

下面是相關的摘錄:

Subsetting rows using multiple conditional statements: There is no limit to how many logical statements may be combined to achieve the subsetting that is desired. The data frame x.sub1 contains only the observations for which the values of the variable y is greater than 2 and for which the variable V1 is greater than 0.6.

x.sub1 <- subset(x.df, y > 2 & V1 > 0.6)

+0

這個鏈接似乎是實際的:http://www.ats.ucla.edu/stat/r/faq/subset_R.htm。不知道,但引用的片段在那裏。 – Marek 2010-06-16 11:57:39