【问题标题】:looping a data frame while performing if statements在执行 if 语句时循环数据帧
【发布时间】:2017-02-28 08:29:18
【问题描述】:

R 新手问题。 我有一个数据框(wealth_df),每行分组为一个五分位数(1 到 5)。我想对每一行进行循环,并找到每个项目对每个五分位数的观察次数并将它们存储在一个表中。

    **   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)

预期输出是:

拥有汽车并处于五分之一的人是:2

拥有汽车且处于五分位数 2 的人是:0

拥有汽车且处于五分位 3 的人是:0

拥有汽车且处于五分位 4 的人是:1

拥有汽车并且处于五分之一的人是:0

等等

【问题讨论】:

  • @Cath,我的错。我已经进行了编辑,任何想法你会怎么做

标签: r loops if-statement


【解决方案1】:

使用包 plyr 中的函数 ddply 通过 Quintile_Score 汇总每个变量:

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

【讨论】:

  • 非常感谢@user3640617
猜你喜欢
  • 1970-01-01
  • 2011-09-24
  • 2019-05-06
  • 1970-01-01
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
相关资源
最近更新 更多