Home > database >  R fill in vector for concentration based on condition
R fill in vector for concentration based on condition

Time:06-03

I am running into the following question: I have the following data.table: starting dataframe

And I have a range of concentrations:

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

what I want to happen is that if same = "no", fill in the concentration range downwards, like this:

result

But what I also want to happen, is that if I added a 7th concentration of a drug to the datatable, I would want that drugs concentration to become NA and then continue. like this:

end result

I Posted this question before but now I have it a bit more detailed.

CodePudding user response:

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

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

df %>%
  group_by(Drug) %>%
  mutate(Concentration = concentration[row_number()])

# A tibble: 16 x 2
# Groups:   Drug [3]
    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       NA     
14     3        0.0001
15     3        0.001 
16     3        0.01
  • Related