如何使用dplyr :: rename_all()将计数值添加到列名?

时间:2018-07-30 15:24:45

标签: r dplyr rename tidyverse

也许我遗漏了一些明显的东西,但是我只想重命名我的所有列,如下所示

library(dplyr); library(tibble); library(datasets)

(df <- datasets::VADeaths %>% as.data.frame %>%
  tibble::rownames_to_column() %>% rename(Age = rowname))
#>     Age Rural Male Rural Female Urban Male Urban Female
#> 1 50-54       11.7          8.7       15.4          8.4
#> 2 55-59       18.1         11.7       24.3         13.6
#> 3 60-64       26.9         20.3       37.0         19.3
#> 4 65-69       41.0         30.9       54.6         35.1
#> 5 70-74       66.0         54.3       71.1         50.0


 df %>% rename(`Rural Male (n = 163.7)` = `Rural Male`)

 #>  Age ID  Rural Male (n = 163.7) Rural Female Urban Male Urban Female
 #> 1 50-54                   11.7          8.7       15.4          8.4
 #> 2 55-59                   18.1         11.7       24.3         13.6
 #> 3 60-64                   26.9         20.3       37.0         19.3
 #> 4 65-69                   41.0         30.9       54.6         35.1
 #> 5 70-74                   66.0         54.3       71.1         50.0

如何使用rename_all添加所有列总和(年龄ID除外)? 即

df %>% rename_all(funs(function(x) = paste(variable, " (n = ", sum(variable), ")")))

https://dplyr.tidyverse.org/reference/select_all.html

1 个答案:

答案 0 :(得分:3)

cols <- setdiff(names(df), "Age")
rename_at(df, cols, funs(paste0(., " (n = ", colSums(df[.]), ")")))

    Age Rural_Male (n = 163.7) Rural_Female (n = 125.9) Urban_Male (n = 202.4) Urban_Female (n = 126.4)
1 50-54                   11.7                      8.7                   15.4                      8.4
2 55-59                   18.1                     11.7                   24.3                     13.6
3 60-64                   26.9                     20.3                   37.0                     19.3
4 65-69                   41.0                     30.9                   54.6                     35.1
5 70-74                   66.0                     54.3                   71.1                     50.0

可复制的数据:

df <- data.frame(
  Age = c("50-54", "55-59", "60-64", "65-69", "70-74"), 
  Rural_Male = c(11.7, 18.1, 26.9, 41, 66), 
  Rural_Female = c(8.7, 11.7, 20.3, 30.9, 54.3), 
  Urban_Male = c(15.4, 24.3, 37, 54.6, 71.1),
  Urban_Female = c(8.4, 13.6, 19.3, 35.1, 50)
)