【问题标题】:Using for loop to filter data frame with different groups in R使用for循环过滤R中不同组的数据帧
【发布时间】:2017-10-04 17:42:06
【问题描述】:

如果我有一个数据框:

d <- data.frame(
  name = c("n1", "n2", "n3", "n4", "n5", "n6", "n7", "n8", "n9", "n10"),
  color = c("blue", "blue", "red", "blue", "red", "blue", "blue", "red", "green", "green"),
weight = c(53, 34, 63, 25, 45, 24, 66, 12, 45, 8),
  gender = c(1, 0, 0, 0, 1 ,1 ,1 , 0, 1, 0)) 

我将如何使用 R 中的 for 循环函数来过滤从平均 每个“颜色”中 +10 的“权重”值?所以我会得到所有行的输出,这些行的权重为每个单独“颜色”的平均值 +10。

我知道d[d$weight &gt; mean(d$weight) + (10 + sd(d$weight)), ] 会给我符合整个样本的这个标准的行,但我试图分别找到每个“颜色”的值,因为每个“颜色”都有不同的 sd 值。

我正在尝试理解 R 中的 for 循环。

【问题讨论】:

  • 嗨,如果你想得到平均值,为什么在你的例子中使用sd?为什么需要使用 for 循环(在R 中通常最好避免使用它们)?
  • 抱歉,我不小心漏掉了那部分,我现在已经修好了。

标签: r for-loop dataframe filter


【解决方案1】:

为此使用for 循环是一个糟糕的主意,但既然你问...

d <- data.frame(
  name = c("n1", "n2", "n3", "n4", "n5", "n6", "n7", "n8", "n9", "n10"),
  color = c("blue", "blue", "red", "blue", "red", "blue", "blue", "red", "green", "green"),
  weight = c(53, 34, 63, 25, 45, 24, 66, 12, 45, 8),
  gender = c(1, 0, 0, 0, 1 ,1 ,1 , 0, 1, 0)) 

d[d$weight > (10 + sd(d$weight)), ]

for (color in unique(d$color)) {
  subd <- d[d$color == color, ]
  print(subd[subd$weight > (10 + sd(subd$weight)), ])
}

【讨论】:

    【解决方案2】:

    我同意@cj-yetman 的观点,即使用for 循环执行此操作并不理想。更好的方法是使用dplyr 分组功能。类似的东西:

    library(dplyr)
    d2 <- d %>% 
      group_by(color) %>% 
      mutate(avg_w = mean(weight, na.rm = T)) %>% 
      filter(abs(weight - avg_w) <= 10)
    
    > d2
    Source: local data frame [2 x 5]
    Groups: color [2]
    
        name  color weight gender avg_w
      <fctr> <fctr>  <dbl>  <dbl> <dbl>
    1     n2   blue     34      0  40.4
    2     n5    red     45      1  40.0
    

    【讨论】:

      【解决方案3】:

      考虑一下基本 R by 函数,它完全按照您的需要:在不同级别的数据帧上运行相同的操作,这里是 color 值。返回的是一个数据帧列表,然后您可以运行 do.call(rbind, ...) 以获得最终数据帧:

      mean_subsetsdflist <- by(d, d$color, function(i) 
           i[i$weight > (mean(i$weight) + (10 + sd(i$weight))), ])
      
      mean_subsetdf <- do.call(rbind, mean_subsetsdflist)
      

      【讨论】:

        猜你喜欢
        • 2021-12-13
        • 1970-01-01
        • 2021-06-25
        • 2018-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多