2016-11-04 5 views
0

data.frameのサブセットを取得しようとしていますが、結果の背後にあるロジックを理解できません。私はSQLで作業することに慣れていたので、行列の値を1つ分けて作業しやすくなると思った。サブセットの背後にあるロジックR

// created a dataset example, with any values and then I combined 
Country <- c('Argentina','Brazil','Chile') 
Quantity <- c(1, seq(5)) 
M <- cbind(Country,Quantity) 
M <- as.data.frame(M) 

// the result 
    Country  Quantity 
1 Argentina  1 
2 Brazil  1 
3 Chile   2 
4 Argentina  3 
5 Brazil  4 
6 Chile   5 

// now I tried to isolated 
test <- M[M$Country=="Brazil",] 

// and still good 
    Country Quantity  
2 Brazil  1  
5 Brazil  4 

私は私のために(*)カウントするように閉じていることを、「表」コマンドを使用すると、カウント結果はOKですが、それはすべての国をもたらし、私はこの結果を理解していない、なぜなら私はブラジルのみをろ過した。

table(test) 

       Quantity 
    Country 1 2 3 4 5 
    Argentina 0 0 0 0 0 
    Brazil  1 0 0 1 0 
    Chile  0 0 0 0 0 

おかげで、

フィリペ

+0

'テーブル(テスト)からの出力は'賢明に見える:あなたは、あなたも不要なレベルを削除するdroplevelsを使用することができ要因が必要な場合はstringsAsFactors = FALSE

M <- data.frame(Country, Quantity, stringsAsFactors=FALSE) test <- M[M$Country=="Brazil",] table(test) # Quantity # Country 1 4 # Brazil 1 1 

で事前に全体のことを避けることができます私に。 –

答えて

0

あなたは要因を持っています。レベルはサブセットの後でさえ維持される。

test <- M[M$Country=="Brazil",] 
test2 <- droplevels(test) 
table(test2) 
#   Quantity 
# Country 1 4 
# Brazil 1 1 
関連する問題