【问题标题】:how to count and sum of the values of a column in a tibble in R?如何计算和汇总R中小标题中列的值?
【发布时间】:2020-11-16 20:42:53
【问题描述】:

例如,我有这个小标题:

       nationality    Other
[1,]          White     1 ------> I want to add
[2,]          Mexican   0
[3,]          American  0
[4,]          Asian     1 -------> I want to add
[5,]          af        1 -------> I want to add
[6,]          American  0

我想以某种方式总结 Other 中的值并创建它自己的 tibble:

       Other
[1,]     3

我尝试使用 sum(),但它给了我

  Error in FUN(X[[i]], ...) : 
  only defined on a data frame with all numeric variables

除此之外,tally() 给了我这个,它计算列中的行数:

      n
1     88

代码如下:

natgroups3 <- ibtclean %>% select(nationality) %>%mutate(Other = ifelse(str_detect(nationality, "af|White|Asian|white|Middle-Eastern"), yes = 1, no = 0)) %>% drop_na() 

【问题讨论】:

  • 试试ibtclean %&gt;% filter(nationality %in% c('White', 'af', 'Asian', 'white', 'Middle-Eastern')) %&gt;% summarise(Other = sum(Other))ibtclean %&gt;% filter(as.logical(Other)) %&gt;% summarise(Other = sum(Other))
  • sum(as.numeric(x)) 怎么样?
  • 谢谢!第一个效果很好,不幸的是, sum(as.numeric()) 给了我一个错误

标签: r dplyr


【解决方案1】:

尝试使用 tidyverse 库。我准备了一个示例代码,它使用您的结构重新创建一个小标题 d 并计算目标小标题 c 与列 other 等于的行数到 1。

library(tidyverse)
d <- tribble(~nationality, ~other, 'White', 0, 'Mexican', 1, 'Amrican', 0, 'Asian', 1, 'af', 1)
d
c <- d %>% count(other) %>% filter(other == 1) %>% select('Other' = n)
c

您也可以选择列other,并使用以下代码计算其总和(根据您的业务需要)

library(tidyverse)
d <- tribble(~nationality, ~other, 'White', 0, 'Mexican', 1, 'Amrican', 0, 'Asian', 1, 'af', 1)
d
c <- d %>% select(other) %>% summarise('Other'=sum(other))
c

两个代码 sn-ps 产生以下结果

# A tibble: 5 x 2
  nationality other
  <chr>       <dbl>
1 White           0
2 Mexican         1
3 Amrican         0
4 Asian           1
5 af              1
# A tibble: 1 x 1
  Other
  <dbl>
1     3

希望这些 sn-ps 能解决您的问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 2021-10-03
    • 2023-01-05
    • 2019-05-05
    • 2019-10-01
    相关资源
    最近更新 更多