簡體   English   中英

R中的聚合函數未正確分配給df

[英]Aggregate function in R not assigning to df correctly

我在R中有一個名為ag的列的數據幀,其中cols a和b是非數字的,其余的是數字的。

當我在控制台中運行以下行時,它會按預期運行-為我提供每個變量的標准差,n和均值:

df %>% 
select(a, b, c, d, e) %>%
aggregate(.~a+b, data = ., FUN = function(x) c(avg = mean(x), std = sd(x, na.rm = TRUE), n = length(x)))

但是,當我嘗試將輸出分配給數據框時,它僅運行均值函數,而不創建標准差或n的列。 為什么會這樣?

當我們使用dplyrgroup_bysummarise/mutate可以獲得預期的輸出

library(dplyr)
df %>% 
   select(a, b, c, d, e) %>%
   group_by(a, b) %>%
   mutate(n = n()) %>%
   group_by(n, add = TRUE) %>%
   summarise_all(funs(mean, sd)) 

關於為什么aggregate的行為不同,我們將兩個或多個函數的輸出串聯起來,它返回的單列具有針對“ c”,“ d”和“ e”的matrix輸出。

str(res)
#'data.frame':   5 obs. of  5 variables:
# $ a: Factor w/ 3 levels "A","B","C": 1 3 1 2 3
# $ b: Factor w/ 2 levels "a","b": 1 1 2 2 2
# $ c: num [1:5, 1:3] -0.495 0.131 0.448 -0.495 -0.3 ...
#  ..- attr(*, "dimnames")=List of 2
#  .. ..$ : NULL
#  .. ..$ : chr  "avg" "std" "n"
# $ d: num [1:5, 1:3] -0.713 1.868 -0.71 -0.508 -0.545 ...
#  ..- attr(*, "dimnames")=List of 2
#  .. ..$ : NULL
#  .. ..$ : chr  "avg" "std" "n"
# $ e: num [1:5, 1:3] -0.893 -0.546 -0.421 1.572 -0.867 ...
#  ..- attr(*, "dimnames")=List of 2
#  .. ..$ : NULL
#  .. ..$ : chr  "avg" "std" "n"

其中res是OP的代碼的輸出

為了將其轉換為普通的data.frame列,請使用

res1 <- do.call(data.frame, res)
str(res1)
#'data.frame':   5 obs. of  11 variables:
# $ a    : Factor w/ 3 levels "A","B","C": 1 3 1 2 3
# $ b    : Factor w/ 2 levels "a","b": 1 1 2 2 2
# $ c.avg: num  -0.495 0.131 0.448 -0.495 -0.3
# $ c.std: num  0.233 NA NA 1.589 1.116
# $ c.n  : num  2 1 1 3 2
# $ d.avg: num  -0.713 1.868 -0.71 -0.508 -0.545
# $ d.std: num  1.365 NA NA 0.727 0.322
# $ d.n  : num  2 1 1 3 2
# $ e.avg: num  -0.893 -0.546 -0.421 1.572 -0.867
# $ e.std: num  0.771 NA NA 1.371 0.255
# $ e.n  : num  2 1 1 3 2

數據

set.seed(24)
df <- data.frame(a = rep(LETTERS[1:3], each = 3), 
   b = sample(letters[1:2], 9, replace = TRUE), 
   c = rnorm(9), d = rnorm(9), e = rnorm(9))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM