简体   繁体   中英

how to count and sum of the values of a column in a tibble in R?

For example, I have this tibble:

       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

I want to somehow sum up the values in Other and create it's own tibble:

       Other
[1,]     3

I tried using sum(), but it gives me

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

In addition to that, tally() gives me this, it counts the number of rows in the column:

      n
1     88

Here is the code:

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

Try to use the tidyverse library. I prepared a sample code that recreates a tibble d with your structure and calculates the target tibble c with the count of rows with the column other equals to 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

You can also select the column other and calculate its sum with the following code (according to your business need)

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

Both of the code snippets produce the following result

# 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

I hope these snippets solve your issue

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