0

Here is an example of my data:

Type <- c('A','A','A','A','B','B','C','D')
Name <- c('DK', 'MO', 'OM', 'LSO', 'GOP', 'ADG','BFC','TMD')
Value <- c(3,2,5,3,6,5,7,6)
Dat <- data.frame(Type, Name,Value)
Dat
  Type Name Value
1    A   DK     3
2    A   MO     2
3    A   OM     5
4    A  LSO     3
5    B  GOP     6
6    B  ADG     5
7    C  BFC     7
8    D  TMD     6

What I'm trying to get is the sum of the value when Type=A. In this case, it is 13. I found some similar examples by applying dplyr, but I don't need the type nor the name. Please help and thank you!

T-T
  • 693
  • 1
  • 10
  • 24
  • 4
    `sum(Dat$Value[Dat$Type == 'A'])` – Sotos May 06 '16 at 16:17
  • 3
    Or, quite similarly `sum(Dat[Dat$Type=="A","Value"])` and `sum(Dat[Dat$Type=="A",]$Value)` and `with(Dat, sum(Value[Type == 'A']))`. – lmo May 06 '16 at 16:19
  • 3
    With `tapply(Dat$Value,Dat$Type,sum)` you get the sum for each group (not just for `A`). There are tons of other ways of doing this. – nicola May 06 '16 at 16:30
  • Or this, `sum(subset(Dat,Dat$Type == 'A')$Value)` as @nicola said, there are countless ways to do this – cgage1 May 06 '16 at 16:54
  • Solved my question perfectly! Thank you all for the suggestions. – T-T May 06 '16 at 17:15
  • Another option with `data.table` `setDT(Dat, key="Type")["A", sum(Value)]` – akrun May 06 '16 at 17:18
  • 1
    @Sotos first comment provided the best answer of the base R candidates because it's the only one that does not do unnecessary subsetting on the entire data set.. – Rich Scriven May 06 '16 at 19:00
  • Shall we just mark as dupe: [r- How to sum a variable by group?](http://stackoverflow.com/q/1660124/903061), or do we think this is different because OP just wants a single level of the group? – Gregor Thomas May 06 '16 at 19:01

1 Answers1

2

Using dplyr you would use group_by to group each type or if you only want type A you could filter where Type == A. Then in both cases you would summarize by the sum of the value. I've shown both examples below.

    library(dplyr)

    Type <- c('A','A','A','A','B','B','C','D')
    Name <- c('DK', 'MO', 'OM', 'LSO', 'GOP', 'ADG','BFC','TMD')
    Value <- c(3,2,5,3,6,5,7,6)
    Dat <- data.frame(Type, Name,Value)
    Dat

    res1 <- Dat %>%
      group_by(Type) %>%
      summarize(sum(Value))
    res1
#    Source: local data frame [4 x 2]
#
#    Type sum(Value)
#  (fctr)      (dbl)
#1      A         13
#2      B         11
#3      C          7
#4      D          6

    res2 <- Dat %>%
      filter(Type == "A") %>%
      summarize(sum(Value))
    res2
#  sum(Value)
#1         13
AllanT
  • 923
  • 11
  • 23