dplyr:为向量中的每个变量名称在摘要中添加新变量

时间:2018-11-29 22:25:15

标签: r dplyr

我有这段代码:

trimmedMeans <- cleaned %>%
    filter(TrackName == t & ToBeTrimmed != 1) %>%
    group_by(TrackName, SpeakerName) %>%
    summarise(Expectation.Mean = mean(Expectation, na.rm = TRUE),
              Expectation.Sd = sd(Expectation, na.rm = TRUE),
              Interesting.Mean = mean(Interesting, na.rm = TRUE),
              Interesting.Sd = sd(Interesting, na.rm = TRUE),
              Useful.Mean = mean(Useful, na.rm = TRUE),
              Useful.Sd = sd(Useful, na.rm = TRUE),
              OralPresentation.Mean = mean(OralPresentation, na.rm = TRUE),
              OralPresentation.Sd = sd(OralPresentation, na.rm = TRUE),
              NumOfVoters = n()
    )

现在假设具有此向量:

myvars <- c("Expectation", "Interesting", "Useful", "OralPresentation")

我想使用向量myvars动态地概括前面的代码块。

1 个答案:

答案 0 :(得分:0)

为此有一个summarise_at

iris
  %>% group_by(Species)
  %>% summarise_at(c("Sepal.Length", "Sepal.Width"), funs(mean, sd), na.rm=TRUE)

# A tibble: 3 x 5
  Species    Sepal.Length_mean Sepal.Width_mean Sepal.Length_sd Sepal.Width_sd
  <fct>                  <dbl>            <dbl>           <dbl>          <dbl>
1 setosa                  5.01             3.43           0.352          0.379
2 versicolor              5.94             2.77           0.516          0.314
3 virginica               6.59             2.97           0.636          0.322