【问题标题】:R: Loop to filter dataframe and print mean of column of filtered data into new dataframeR:循环过滤数据帧并将过滤数据列的平均值打印到新数据帧中
【发布时间】:2020-08-05 13:55:30
【问题描述】:

我有一个名为 PlantGroNoT.RCP2.first.0 的数据框(使用 dput() 随机采样)。

structure(list(Year = c(2040L, 2068L, 2096L, 2049L, 2072L, 2042L, 
2087L, 2047L, 2076L, 2075L, 2052L, 2054L, 2034L, 2060L, 2041L, 
2031L, 2067L, 2080L, 2055L, 2067L, 2095L, 2097L, 2097L, 2077L, 
2057L, 2038L, 2052L, 2095L, 2043L, 2075L), DOY = c(78L, 13L, 
20L, 364L, 23L, 14L, 352L, 72L, 54L, 2L, 1L, 5L, 53L, 43L, 63L, 
26L, 21L, 30L, 360L, 22L, 46L, 62L, 355L, 4L, 61L, 355L, 75L, 
51L, 46L, 39L), DAP = c(93L, 28L, 35L, 14L, 38L, 29L, 2L, 87L, 
69L, 17L, 16L, 20L, 68L, 58L, 79L, 41L, 36L, 45L, 10L, 37L, 61L, 
78L, 5L, 20L, 77L, 5L, 90L, 66L, 61L, 54L), NSTD = c(0.244, 0, 
0.023, 0, 0, 0, 0, 0.547, 0, 0, 0, 0, 0, 0, 0.148, 0, 0, 0.001, 
0, 0, 0.186, 0.443, 0, 0, 0.278, 0, 0.403, 0.16, 0.085, 0.069
), RCP = c("2", "4", "4", "4", "2", "4", "8", "4", "8", "4", 
"4", "4", "8", "4", "4", "2", "8", "8", "8", "4", "8", "2", "4", 
"8", "4", "8", "4", "4", "8", "2")), row.names = c(5634575L, 
1218676L, 788139L, 7051284L, 6262001L, 1122307L, 3560772L, 3925983L, 
2584130L, 3401700L, 1217186L, 1455727L, 2993448L, 597952L, 5893799L, 
6696664L, 2345802L, 3105731L, 6347255L, 5005396L, 3330449L, 780805L, 
2522272L, 3668256L, 2099405L, 818891L, 1123257L, 5237622L, 1259779L, 
1623133L), class = "data.frame")

我想通过RCPDAPYear对其进行过滤。从这个过滤器的结果中,我想取NSTD的平均值并将其打印到数据框HO1_2020_RCP2_stressNSTDmean列中

DAP 的范围从 0 到 114,所以在 HO1_2020_RCP2_stress$WSPDmean 的第一个单元格中,我希望有 DAP==0 的 NSTDmean,在第二个单元格中是 DAP==1 的平均值,等等。

我创建了这个循环来完成这项工作。

i = -1
  repeat{
    i= i+1
    PlantGroNoT.RCP2.first.0 <- filter(PlantGroNoT_1, RCP==2 & DAP==i & Year<=2060)
    H01_2020_RCP2_stress$NSTDmean <- mean(PlantGroNoT.RCP2.first.0$NSTD, na.rm=TRUE)
    if (i>114)
      break
  }

过滤器和均值计算本身起作用。

但是,循环不会在HO1_2020_RCP2_stress$WSPDmean 列中正确返回NSTDmean。它总是打印整个 NSTDmean 列的最后一个 i 的值(即这里的 DAS==114)。

【问题讨论】:

  • hm,subset(PlantGroNoT_1, RCP==2 &amp; Year&lt;2060) 只有两个观察结果。最终对于原始数据框with(PlantGroNoT_1, tapply(NSTD, DAP, FUN=mean, na.rm=TRUE)) ?
  • 谢谢!它确实有效:subset &lt;- subset(PlantGroNoT_1, RCP==2 &amp; Year&lt;=2060) with &lt;- with(subset, tapply(NSTD, DAP, FUN=mean, na.rm=TRUE)) H01_2020_RCP2_stress$NSTDmean &lt;- with
  • 通常情况下,对用户定义的对象使用 R 函数的名称不是一个好主意。

标签: r filter dplyr mean repeat


【解决方案1】:

我希望我不会误解您想要做什么,但我认为使用 group_by 是一种有效的方法:

df %>%
  filter(RCP == 2 & Year <= 2060) %>% # These are the only conditions and they are fixed
  group_by(DAP) %>%
  summarise(NTSDT = mean(NSTD,na.rm =TRUE)) %>%
  arrange(DAP)

这会将数据框过滤为仅 RCP == 2 且年份

如果您需要将此结果附加到原始数据框,您可以简单地加入它或使用mutate 而不是汇总。

【讨论】:

  • 完美,这正是我想做的!我正在努力处理其他 dplyr 命令。谢谢!!
猜你喜欢
  • 2011-08-28
  • 1970-01-01
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
  • 2021-11-21
  • 2012-08-13
  • 2018-02-20
  • 2020-01-16
相关资源
最近更新 更多