Home > Software engineering >  assign a vector with concentrations to a dataframe R
assign a vector with concentrations to a dataframe R

Time:06-02

Lets say I have the following data frame. start dataframe

and I have a vector containing concentrations:

concentration <- c(0.0001, 0.001, 0.01, 0.1, 1, 10)

and what I want to do is: if same = no. fill in the concentrations for that drug. so it will look like this: end result

Would there be a way to automate this?

CodePudding user response:

df$Concentration = rep(c(0.0001, 0.001, 0.01, 0.1, 1, 10), length.out = nrow(df))

CodePudding user response:

Assuming that concentrations start always with the lowest (0.0001) and that any increase is a 10 times higher, you can easily generate it based on the Drug id, without the need of the "same" column.

df <- data.frame(Drug = c(rep(1, 6), rep(2, 7)))

df %>%
  group_by(Drug) %>%
  mutate(Concentration = 0.0001 * 10^(row_number()-1))


    Drug Concentration
   <dbl>         <dbl>
 1     1        0.0001
 2     1        0.001 
 3     1        0.01  
 4     1        0.1   
 5     1        1     
 6     1       10     
 7     2        0.0001
 8     2        0.001 
 9     2        0.01  
10     2        0.1   
11     2        1     
12     2       10     
13     2      100
  • Related