1

I have a dataset column with different medical specialties but the specialties repeat and for each row there is a count. I want to sum the values for each specialty and also ignore the rows with less than 10. How do I do this in R?

For Ex:

        Col1   Col2 
Internal Med     11
Internal Med     12
   Neurology      5
   Neurology     13
Internal Med      9

I should get Internal Med- 12 + 11 (9 is ignored) Neurology- 13 (5 is ignored)

joel.wilson
  • 8,243
  • 5
  • 28
  • 48
kobe2792
  • 39
  • 3

4 Answers4

1
# method 1:
library(data.table)
setDT(df)[Col2 > 10, sum(Col2),by = .(Col1)]

# OR
# method 2
library(dplyr)
df %>% group_by(Col1) %>% 
       filter(Col2 > 10) %>% 
       summarise(sum(Col2))

#           Col1 `sum(Col2)`
# 1 Internal_Med          23
# 2    Neurology          13
joel.wilson
  • 8,243
  • 5
  • 28
  • 48
0

purly base based solution :

data <- data.frame(
Col1=c("IM", "IM", "N", "N", "IM"),
Col2=c(11, 12, 5, 13, 9)
)

# sums in groups
aggregate(data$Col2, by=list(data$Col1), FUN=sum)

# sums in groups for obs with Col2 >=10
aggregate(data$Col2[data$Col2>=10], by=list(data$Col1[data$Col2>=10]), FUN=sum)

(but I prefer dplyr)

Qbik
  • 5,885
  • 14
  • 62
  • 93
0

With base R:

aggregate(Col2~Col1, subset(df, Col2 >= 10), sum)
#            Col1 Col2
#1   Internal Med   23
#2      Neurology   13

or

subdf <- subset(df, Col2 >= 10)
as.data.frame(Col2=tapply(subdf$Col2, subdf$Col1, sum))
#               Col2
# Internal Med   23
# Neurology      13
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63
0

The simplest would be using xtabs:

xtabs( Col2 ~ Col1, df, subset = Col2>10 )
Jealie
  • 6,157
  • 2
  • 33
  • 36