【问题标题】:Fastest way of using conditions in for loop在 for 循环中使用条件的最快方法
【发布时间】:2020-03-26 23:02:09
【问题描述】:

因此,对于数据集 birthwt,我想要从吸烟且出生时未满 20 岁的母亲所生的低体重婴儿的百分比。换句话说,我想要年龄

我运行接下来的三段代码,实际上给出了正确的答案:

 # new df with the conditions
new_df <- subset(birthwt, age<20 & smoke==1)

 #for loop to calculate the low weight

low_weight <- 0
for (i in 1:length(new_df$bwt)){
  if(bwt[i] < 2600){
    low_weight <- low_weight + 1
  }
}

 #low weight for the original dataset
low_weight_tot <- 0
attach(birthwt)
for (i in 1:length(birthwt$bwt)){
  if(bwt[i] < 2600){
    low_weight_tot <- low_weight_tot + 1
  }
}

print(low_weight/low_weight_tot)*100

但是我觉得这很乏味,有没有其他更简单的方法可以用循环来做到这一点?

谢谢!

【问题讨论】:

  • 有什么乏味的?
  • 而且它需要是一个循环?
  • 这个百分比的分母是什么:​​所有婴儿还是只有低出生体重 (
  • 它在实际中不需要是一个循环,但它确实是为了练习的目的。分母将是出生婴儿的总数。感谢您的回答!

标签: r loops for-loop


【解决方案1】:

你不需要循环:

library(dplyr)
birthwt %>% 
  summarise(perc = mean(age < 20 & smoke == 1 & bwt < 2600))

【讨论】:

    【解决方案2】:

    一个for循环就足够了。

    #df contains the birthwt data
    
    lwt_tot <- 0
    lwt_2600 <- 0
    
    for(i in 1:nrow(df)){
      lwt_tot <- lwt_tot + 1
    
      if(df$age[i] < 20 & df$smoke[i] == 1 & df$bwt[i] < 2600){
        lwt_2600 <- lwt_2600 + 1
      }
    
    }
    
    print((lwt_2600/lwt_tot)*100)
    #[1] 3.703704
    

    【讨论】:

      【解决方案3】:

      我想要母亲所生的低体重婴儿的百分比 那个抽烟的,出生时不到20岁

      这建议使用以下代码:

      birthwt %>% 
         filter(bwt<2600) %>%
         group_by(`young(<20)`=age<20, smoke) %>%
         summarise(n = n()) %>%
         ungroup() %>%
         mutate(pct=100*n/sum(n)) 
      

      # A tibble: 4 x 4
        `young(<20)` smoke     n   pct
        <lgl>        <int> <int> <dbl>
      1 FALSE            0    22  34.9
      2 FALSE            1    25  39.7
      3 TRUE             0     9  14.3
      4 TRUE             1     7  11.1
      

      最后一行是你的答案,和你的代码给出的一样。

      【讨论】:

        【解决方案4】:

        在基数 R 中,我们可以计算 age &lt; 20 smoke = 1bwt &lt; 2600 的人数,然后除以 bwt &lt; 2600 的总人数。

        with(birthwt, sum(age < 20 & smoke == 1 & bwt < 2600)/sum(bwt < 2600)) * 100
        #[1] 11.11
        

        【讨论】:

          猜你喜欢
          • 2017-08-16
          • 2012-07-29
          • 2019-09-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多