I want to add an extra row for each subject ID in the data frame (below). This row should have TIME=0
and DV=0
. Other values in the other columns should stay the same. The data frame looks like the following:
ID TIME DV DOSE pH
1 1 5 50 4.6
1 5 10 50 4.6
2 1 6 100 6.0
2 7 10 100 6.0
After adding the extra row, it should look like this:
ID TIME DV DOSE pH
1 0 0 50 4.6
1 1 5 50 4.6
1 5 10 50 4.6
2 0 0 100 6.0
2 1 6 100 6.0
2 7 10 100 6.0
How could I achieve this in R?
Try this:
#dummy data
df <- read.table(text="ID TIME DV DOSE pH
1 1 5 50 4.6
1 5 10 50 4.6
2 1 6 100 6.0
2 7 10 100 6.0",header=TRUE)
#data with zeros
df1 <- df
df1[,c(2,3)] <- 0
df1 <- unique(df1)
#rowbind and sort
res <- rbind(df,df1)
res <- res[order(res$ID,res$TIME),]
res
# ID TIME DV DOSE pH
# 11 1 0 0 50 4.6
# 1 1 1 5 50 4.6
# 2 1 5 10 50 4.6
# 31 2 0 0 100 6.0
# 3 2 1 6 100 6.0
# 4 2 7 10 100 6.0
Here's another possible data.table
solution
library(data.table)
setDT(df)[, .SD[c(1L, seq_len(.N))], ID][,
indx := seq_len(.N), ID][indx == 1L, 2:3 := 0][]
# ID TIME DV DOSE pH indx
# 1: 1 0 0 50 4.6 1
# 2: 1 1 5 50 4.6 2
# 3: 1 5 10 50 4.6 3
# 4: 2 0 0 100 6.0 1
# 5: 2 1 6 100 6.0 2
# 6: 2 7 10 100 6.0 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With