简体   繁体   中英

A list contain column names and using the list to reference the tibble in R

The table contain My Name, My Age , My Height. I would like to store in a list to get the summary of the height instead of using test = My Height

list<- c("`My Name`" , "`My Age`" , "`My Height`" )

table%>%
group_by(`My Name` ,`My Age`,`My Height` ) %>%
summarize(test = mean(list[3], na.rm = TRUE))

Try summarize_at :

library(dplyr)
lst<- c("`My Name`" , "`My Age`" , "`My Height`" )

table%>%
  group_by(`My Name` ,`My Age`,`My Height` ) %>%
  summarize_at(vars(lst[3]), mean, na.rm = TRUE)

Or using non-standard evaluation :

table %>%
  group_by(`My Name` ,`My Age`,`My Height` ) %>%
  summarise(test = mean(!!sym(lst[2]), na.rm = TRUE))

Using reproducble example form mtcars

lst <- c('cyl', 'hp', 'am')

mtcars %>%
  group_by(cyl) %>%
  summarise_at(vars(list[2]), mean, na.rm  =TRUE)

# A tibble: 3 x 2
#    cyl  test
#  <dbl> <dbl>
#1     4  82.6
#2     6 122. 
#3     8 209. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM