mardi 28 février 2017

looping a data frame while performing if statements

R newbie question. I have a data frame (wealth_df) with each row grouped into a quintile (1 to 4). I want to do loop on each row and find the number of observation each item has for each quintile and store them in a table.

    **   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     0       0         0     0     4

I have done the following but its too tedious since the data frame is big.

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)

etc

Aucun commentaire:

Enregistrer un commentaire