I have the following test data:
df <- data.frame(group = c('Control' , 'Low' , 'Middle' , 'High') ,
type = c('A' , 'A' , 'A' , 'A') ,
value = c('3' , '5' , '2' , '4'))
I'm attempting to find each ratio for the values of "Low" , "Middle" , "High" against the value for "Control" - Low/Control, Middle/Control , High/Control.
I've trying this using mutate and ifelse, however, the function returns an NA.
df %>%
group_by(group) |>
mutate(value = ifelse(group == 'Low' , value / value[Trt == 'Control'] , value))
I'd like to find a function that will return the appropriate result for each of the ratios.
CodePudding user response:
The group_by seems to be 'type' column (based on the input data)
library(dplyr)
df <- df %>%
type.convert(as.is = TRUE) %>%
group_by(type) %>%
mutate(value1 = value/value[group == "Control"]) %>%
ungroup
-output
df
# A tibble: 4 × 4
group type value value1
<chr> <chr> <int> <dbl>
1 Control A 3 1
2 Low A 5 1.67
3 Middle A 2 0.667
4 High A 4 1.33