[R] how to add new rows in a dataframe?
arun
smartpink111 at yahoo.com
Mon Apr 29 17:12:08 CEST 2013
Hi,
dat1<- read.table(text="
id t scores
2 0 1.2
2 2 2.3
2 3 3.6
2 4 5.6
2 6 7.8
3 0 1.6
3 1 1.2
3 4 1.5
",sep="",header=TRUE)
library(zoo)
res1<-do.call(rbind,lapply(split(dat1,dat1$id),function(x) {t1<-seq(min(x$t),max(x$t));scores1<-na.locf(x$scores[match(t1,x$t)]);data.frame(id=rep(unique(x$id),length(t1)),t1,scores1)}))
row.names(res1)<- 1:nrow(res1)
res1
# id t1 scores1
#1 2 0 1.2
#2 2 1 1.2
#3 2 2 2.3
#4 2 3 3.6
#5 2 4 5.6
#6 2 5 5.6
#7 2 6 7.8
#8 3 0 1.6
#9 3 1 1.2
#10 3 2 1.2
#11 3 3 1.2
#12 3 4 1.5
libray(plyr)
dat2<-ddply(dat1,.(id),summarize,t=seq(min(t),max(t)))
res2<-mutate(join(dat2,dat1,type="full"),scores=na.locf(scores))
identical(res1,res2)
#[1] TRUE
res2
# id t scores
#1 2 0 1.2
#2 2 1 1.2
#3 2 2 2.3
#4 2 3 3.6
#5 2 4 5.6
#6 2 5 5.6
#7 2 6 7.8
#8 3 0 1.6
#9 3 1 1.2
#10 3 2 1.2
#11 3 3 1.2
#12 3 4 1.5
A.K.
>Hello , dear experts,
>I have my data like this:
>
>id t scores
>2 0 1.2
>2 2 2.3
>2 3 3.6
>2 4 5.6
>2 6 7.8
>3 0 1.6
>3 1 1.2
>3 4 1.5
>
>I want to fullifill the "t", so i want to add the rows with the data of (t-1)
>
>just get another dataframe like this:
>
>id t scores
>2 0 1.2
>2 1 1.2
>2 2 2.3
>2 3 3.6
>2 4 5.6
>2 5 5.6
>2 6 7.8
>3 0 1.6
>3 1 1.2
>3 2 1.2
>3 4 1.5
>
>How can i get the result like this? In reality, i have 4000 obervations, so it's difficult to add the lines manuelly.
>
>Thank you so much.
More information about the R-help
mailing list