我有下表,我必須為 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
uj5u.com熱心網友回復:
我們不需要mutate(mutate創建或轉換列)。在這里,所需的輸出是每組一行,可以使用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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/312482.html
上一篇:在dplyr::mutate中包裝purrr::map時的奇怪行為
下一篇:如何為R中的每個參與者生成ID
