2017-02-28 32 views
-1

R新手問題。 我有一個數據框(wealth_df),每行分組爲一個五分位數(1到5)。我想在每一行上做循環,並找出每個項目對每個五分位數的觀察次數,並將它們存儲在一個表中。在執行if語句時循環數據幀

** Car Bicycle Motorcycle Boat House Quintiles_Score** 
    1 0.5 0.2  0.4  0.6 0.8 1 
    2 0  0.2  0.4  0  0  2 
    3 0.5 0  0.4  0.6 0  1 
    4 0  0.2  0   0  0  3  
    5 0  0  0.4  0  0.8 4 
    6 0.5 0  0   0  0  4 

我已經完成了以下工作,但由於數據框很大,所以過於繁瑣。

library(Tidyverse) 
#owns a car and in quintile 1 
Car_Q1 <- filter(wealth_df, wealth_df$car == 0.5 & wealth_df$Quintile == 1) 
No_CarQ1 <- nrow(CarQ1) 
print(No_CarQ1) 

#owns a boat and in quintile 4 
Boat_Q4 <- filter(wealth_df, wealth_df$Boat == 0.8 & wealth_df$Quintile == 4) 
No_BoatQ4 <- nrow(BoatQ4) 
print(No_BoatQ4) 

預期輸出是:

人擁有汽車,並且在分位1是:2-

人擁有汽車,並且在分位2:0

人擁有汽車和是在五分之三是:0

擁有汽車和在五分之四的人是:1

人擁有汽車,並在5五分之一是:0

+0

@Cath,是我不好。我已經做了編輯,任何想法你會怎麼做呢 – shja

回答

0

使用從包plyr ddply功能通過Quintile_Score總結每個變量:

ddply(wealth_df, .(Quintiles_Score..), summarize, 
Car=length(Car[Car!=0]), Bicycle=length(Bicycle[Bicycle!=0])) 
+0

Thankssssssssss很多@ user3640617 – shja