【问题标题】:Using dplyr to group the new calculations into one data frame使用 dplyr 将新计算分组到一个数据帧中
【发布时间】:2021-12-02 09:09:47
【问题描述】:

我有下表,对于 x 的每个 唯一 值,我必须获得 y 的标准偏差。

  ID    x   y

   1    1   4   
   2    2   3   
   3    3   7   
   4    1   2   
   5    2   6   
   6    3   8   

例如 x 的每个唯一值,我有 y=4 和 y=2,所以标准差将为:

x1 <- c(4,2)
sd(x1) 
#output is 1.41

x2 <-c(3,6)
sd(x2)
#output is 2.21

x3 <-c(3,6)
sd(x3)
#output is 0.71

有没有一种方法可以使用 dplyr 和管道更快地完成每个输出并将其放入数据帧中?我尝试使用 mutate 和 group_by,但它似乎不起作用。我希望结果看起来像 count_y (每个唯一 x 的 y 值的#)

x   count_y  Std_Dev
    
1   2        1.41
2   2        2.21
3   2        0.71

【问题讨论】:

  • 试试df1 %&gt;% group_by(x) %&gt;% summarise(count_y = n(), Std_Dev = sd(y))
  • @akrun 有效!谢谢。

标签: r dplyr pipe tidyverse data-cleaning


【解决方案1】:

我们不需要mutatemutate 创建或转换列)。这里,需要的输出是每组一行,可以使用summarise

library(dplyr)
df1 %>% 
   group_by(x) %>%
   summarise(count_y = n(), Std_Dev = sd(y))

-输出

# A tibble: 3 × 3
      x count_y Std_Dev
  <int>   <int>   <dbl>
1     1       2   1.41 
2     2       2   2.12 
3     3       2   0.707

数据

df1 <- structure(list(ID = 1:6, x = c(1L, 2L, 3L, 1L, 2L, 3L), y = c(4L, 
3L, 7L, 2L, 6L, 8L)), class = "data.frame", row.names = c(NA, 
-6L))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多