How to split row groups with dplyr?

I have this framework:

x <- data.frame(
    name = rep(letters[1:4], each = 2),
    condition = rep(c("A", "B"), times = 4),
    value = c(2,10,4,20,8,40,20,100)
) 
#   name condition value
# 1    a         A     2
# 2    a         B    10
# 3    b         A     4
# 4    b         B    20
# 5    c         A     8
# 6    c         B    40
# 7    d         A    20
# 8    d         B   100

I want to group by name and divide the value of the lines with condition == "B"by those that are with condition == "A"to get the following:

data.frame(
    name = letters[1:4],
    value = c(5,5,5,5)
)
#   name value
# 1    a     5
# 2    b     5
# 3    c     5
# 4    d     5

I know something like this can get me pretty close:

x$value[which(x$condition == "B")]/x$value[which(x$condition == "A")]

but I was wondering if there is an easy way to do this with dplyr (My dataframe is an example of a toy, and I got to it, catching a few calls group_byand summarise).

+4
source share
3 answers

Try:

x %>% 
  group_by(name) %>%
  summarise(value = value[condition == "B"] / value[condition == "A"])

What gives:

#Source: local data frame [4 x 2]
#
#    name value
#  (fctr) (dbl)
#1      a     5
#2      b     5
#3      c     5
#4      d     5
+8
source

I would use spreadof tidyr.

library(dplyr)
library(tidyr)

x %>%
  spread(condition, value) %>%
  mutate(value = B/A)

  name  A   B value
1    a  2  10     5
2    b  4  20     5
3    c  8  40     5
4    d 20 100     5

Then you can do select(-A, -B)to remove additional columns.

+5

Using data.table, convert 'data.frame' to 'data.table' ( setDT(x)), grouped by 'name', we divide the 'value' corresponding to condition 'B' into those that correspond to condition 'A'.

library(data.table)
setDT(x)[,.(value = value[condition=="B"]/value[condition=="A"]) , name]
#    name value
#1:    a     5
#2:    b     5
#3:    c     5
#4:    d     5

Or, change the shape from “long” to “wide” and divide the column “B” by “A”.

dcast(setDT(x), name~condition, value.var='value')[, .(name, value = B/A)]
+2
source

All Articles