【问题标题】:Plot the sum of all but one variable绘制除一个变量之外的所有变量的总和
【发布时间】:2018-12-09 00:12:31
【问题描述】:

我有一个数据框,其中包含三个不同国家(加拿大、墨西哥、美国)的受访者在两个不同时间点(现在和之前)拥有的电视和收音机数量的数据:

DF <- data.frame(TV_now = as.numeric(c(4, 9, 1, 0, 4, NA)),
                 TV_before = as.numeric(c(4, 1, 2, 4, 5, 2)),
                 Radio_now = as.numeric(c(4, 5, 1, 5, 6, 9)),
                 Radio_before = as.numeric(c(6, 5, 3, 6, 7, 10)),
                 Country = as.factor(c("Mexico", "Canada", "US", "US", "Canada", "US")))

我想对每个变量的总值求和,然后创建一个条形图,显示每个国家/地区的受访者现在和之前拥有的电视和收音机的数量。

现在,如果我的数据框不包含 Country 因子,我可以用这种方式生成图:

library(tidyverse)
library(ggplot2)

DF %>% mutate_all(funs(sum), na.rm = TRUE) %>%
  gather(key=Device, value=Number) %>% 
  ggplot(aes(x=Device,fill=Device)) + 
  geom_bar(aes(x = Device, y = Number), position = "dodge", stat = "identity")

然而,变化

DF %>% mutate_all(funs(sum), na.rm = TRUE) %>%
  gather(key=Device, value=Number, -Country) %>% 
  ggplot(aes(x=Device,fill=Device)) + 
  geom_bar(aes(x = Device, y = Number), position = "dodge", stat = "identity") +
  facet_wrap(~Country)

导致错误:

Error in mutate_impl(.data, dots) : 
  Evaluation error: ‘sum’ not meaningful for factors.

有没有办法从sum 中排除该因素,或者另一种方法来生成预期的情节?

【问题讨论】:

    标签: r ggplot2 tidyr


    【解决方案1】:

    您可以使用汇总函数来汇总不同的列。下面我使用 dplyr 的 summarise_if() 函数总结了数值列。

    DF <- data.frame(TV_now = as.numeric(c(4, 9, 1, 0, 4, NA)),
                 TV_before = as.numeric(c(4, 1, 2, 4, 5, 2)),
                 Radio_now = as.numeric(c(4, 5, 1, 5, 6, 9)),
                 Radio_before = as.numeric(c(6, 5, 3, 6, 7, 10)),
                 Country = as.factor(c("Mexico", "Canada", "US", "US", "Canada", "US")))
    
    DF %>%
            group_by(Country) %>%
            summarise_if(is.numeric,sum,na.rm=TRUE) %>%
            gather(key=Device, value=Number, -Country) %>% 
            ggplot(aes(x=Device,fill=Device)) + 
            geom_bar(aes(x = Device, y = Number),position = "dodge", stat = "identity") + 
            facet_wrap(~Country)
    

    结果是:

    【讨论】:

    • 这是完美的。正是我想要的。
    猜你喜欢
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2018-11-30
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 2019-02-11
    相关资源
    最近更新 更多