我有一個總結為透視表的資料框架,我想在每一個數字列的平均值上添加一行,對于字符列,該行可以被命名為 "平均值"
。資料框架的樣本如下
dat < - c('2000-01-15'>。 '2003-01-15', '2000-02-15',
'2003-02-15',/span>'2000-04-15'。 '2002-04-15',
'2000-12-15',/span>'2002-12-15'。 '2003-12-13', "2003-12-15"。 '2002-02-21', '2002-01-25', '2003-04-24')
df <- data.frame(date =as. Date(dat)。 id = c(1。 2, 3。 4, 5, 6, 7, 8, 9, 10, 11, 12,13),
銷售 = c(134。 211。 2000, 234, 421, 400, 34, 1233, 1222, 1034, 8034, 1234, 2331))
df <- df %>%
mutate(年=格式(日期。 "%Y"),
月=格式(date, "%b") %> % select(-date) %>%
group_by(year,month) %>%
總結(收入= sum(sales))
df2 <- df %> % pivot_wider(id_cols = year, names_from = month, values_from = revenue)
從這里我想做的是
rbind(df2。 summarise_all(df2, mean))
然而,主要的復雜問題是如何回傳數字列的平均值,并回傳一個非數字列的字符。
我想要的輸出應該是
year Apr Dec Feb Jan
<chr> <dbl> < dbl> <dbl> < dbl>
1 2000 421 34 2000 134
2 2002 400 1233 8034 1234
3 2003 2331 2256 234 211
4 平均 1051. 1174. 3423. 526.
uj5u.com熱心網友回復:
我們可以adorn_totals在最后添加一個和行,然后除以總行數-1
library(dplyr)
library(janitor)
df2 %> %
adorn_totals(name = "mean") %>%
mutate(across(where( is. numeric),
~ replace(. , n(), 。 [n()]/(n()-1)))) %> %
as_tibble
輸出
# A tibble: 4 x 5
年 四月 十二月 二月 一月
<chr> <dbl> < dbl> <dbl> < dbl>
1 2000 421 34 2000 134
2 2002 400 1233 8034 1234
3 2003 2331 2256 234 211
4 平均 1051. 1174. 3423. 526.
或者另一個選擇是利用summarise與across在最后連接(c())一個mean值
df2 %>%
解除分組 %>%
總結(年= c(年。 'mean'),
across(where(is. numeric), ~ c(. ,平均(. )))。
輸出
# A tibble: 4 x 5
年 四月 十二月 二月 一月
<chr> <dbl> < dbl> <dbl> < dbl>
1 2000 421 34 2000 134
2 2002 400 1233 8034 1234
3 2003 2331 2256 234 211
4 平均 1051. 1174. 3423. 526.
或者使用add_row從tibble
library(tibble)
df2 %>%
ungroup%>%
add_row(year = 'mean'/span>, ! !! colMeans(. [-1]))
# A tibble: 4 x 5
年 四月 十二月 二月 一月
<chr> <dbl> < dbl> <dbl> < dbl>
1 2000 421 34 2000 134
2 2002 400 1233 8034 1234
3 2003 2331 2256 234 211
4 平均 1051. 1174. 3423. 526.
uj5u.com熱心網友回復:
基礎R選項-
rbind(df2, data. frame(year = 'mean', t(colMeans(df2[-1])))
# year Apr Dec Feb Jan
# <chr> <dbl> <dbl> <dbl>
#1 2000 421 34 2000 134
#2 2002 400 1233 8034 1234
#3 2003 2331 2256 234 211
#4 平均1051. 1174. 3423. 526.
如果你不知道數字列的位置,想動態地識別它們,你可以使用-
cols <- sapply(df2, is. numeric)
rbind(df2, data. frame(year = 'mean'/span>, t(colMeans(df2[cols]))))。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/322167.html
標籤:
下一篇:在R中回傳命名串列的函式
