【问题标题】:Summarise(across(where)) in R [duplicate]R中的总结(跨越(哪里))[重复]
【发布时间】:2021-03-03 21:59:04
【问题描述】:

我有以下名为“data_2”的数据文件:

Person Weight Height
A      55     155
B      65     165
C      75     175

我想使用 Summarise(across(where)) 命令来生成每个人的总重量和重量。这是我到目前为止所尝试的。

data_2 <- read_excel("data_2.xlsx", sheet = 2)


data_2 %>%
summarise(across(where(is.numeric), sum))

很遗憾,这无法正常工作。有没有人知道如何解决这个问题?

预期输出:

Person Weight 
A      55     
B      65     
C      75
Total  195   

【问题讨论】:

  • 也许是这个? data_2 %&gt;% group_by(Person) %&gt;% summarise(across(where(is.numeric), sum))
  • 这也会生成高度列。另外,我不知道总重量。
  • 您需要一个总重量为 195 的新列吗?你能分享你的预期输出吗?
  • 我已经编辑了问题,以便您现在可以看到预期的输出。
  • df[1:2] %&gt;% janitor::adorn_totals()

标签: r summarize across


【解决方案1】:

试试这个:

library(dplyr)
#Code
newdf <- data_2 %>%
  bind_rows(data_2 %>% select(-1) %>%
              summarise_all(sum) %>% mutate(Person='Total'))

输出:

  Person Weight Height
1      A     55    155
2      B     65    165
3      C     75    175
4  Total    195    495

或使用您的代码:

#Code 2
newdf <- data_2 %>% 
  bind_rows(data_2 %>% summarise(across(where(is.numeric),sum)) %>%
              mutate(Person='Total')) %>% select(-Height)

输出:

  Person Weight
1      A     55
2      B     65
3      C     75
4  Total    195

【讨论】:

  • 但我不想打印高度列。只有重量。
  • @JohnDoe 检查解决方案中的最后一个代码!
  • @JohnDoe 或试试newdf &lt;- data_2 %&gt;% select(-Height) %&gt;% bind_rows(data_2 %&gt;% summarise(across(starts_with('Weight'),sum)) %&gt;% mutate(Person='Total'))
  • 该解决方案有效,但是如果我有一个较长的文件,其中包含 N 个人,它只会显示 10 个第一个人 (Person A -J) 的 tibble。它将生成一个 15 x 1 的小标题,但只有前 10 个是可见的。我怎样才能同时显示其他观察结果(人 K - N,+ 总计)?
  • @JohnDoe 在新的数据框中,它将是您拥有的所有人。如果你想在控制台上打印所有人试试这个data_2 %&gt;% select(-Height) %&gt;% bind_rows(data_2 %&gt;% summarise(across(starts_with('Weight'),sum)) %&gt;% mutate(Person='Total')) %&gt;% data.frame()
猜你喜欢
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
相关资源
最近更新 更多