Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an extra row for each subject ID and maintaining the values in the other columns

Tags:

r

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?

like image 396
Amer Avatar asked Feb 11 '15 12:02

Amer


2 Answers

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
like image 124
zx8754 Avatar answered Sep 28 '22 03:09

zx8754


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
like image 25
David Arenburg Avatar answered Sep 28 '22 02:09

David Arenburg