Divide by a specified member in a group in R

1

I'd like to divide the values of t2~t4 by t1 in each group in R from the data like below.

group   type    value
A   t1  10
A   t2  20
A   t3  30
A   t4  40
B   t1  20
B   t2  40
B   t3  60
B   t4  80

I tried to un-melt by type but I think there would be better way to do it.

Any ideas?

Thank you!


R


dplyr

• 141 views

updated 2 hours ago by

★

1.1k

written 5 hours ago by

▴

620

Does this work?

library(dplyr)
library(magrittr)

df <- read.table(text = "group   type    value
A   t1  10
A   t2  20
A   t3  30
A   t4  40
B   t1  20
B   t2  40
B   t3  60
B   t4  80
", header = TRUE)

df %>% 
  group_by(group) %>% 
  mutate(t1val = value[1]) %>% 
  ungroup() %>% 
  mutate(oth_by_t1 = value/t1val)

# # A tibble: 8 x 5
#   group type  value t1val oth_by_t1
#   <chr> <chr> <int> <int>     <dbl>
# 1 A     t1       10    10         1
# 2 A     t2       20    10         2
# 3 A     t3       30    10         3
# 4 A     t4       40    10         4
# 5 B     t1       20    20         1
# 6 B     t2       40    20         2
# 7 B     t3       60    20         3
# 8 B     t4       80    20         4

You could, of course, skip that extra assignment (mutate(t1val = value[1])), and just have this instead (it works all the same):

df %>% 
  group_by(group) %>% 
  mutate(oth_by_t1 = value/value[1]) %>%
  ungroup()


Login
before adding your answer.

Traffic: 2323 users visited in the last hour



Source link