Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend a dataframe based on the last known value [duplicate]

Tags:

r

Is it possible to extend a database based on the last value?

For example:

 x <- c(1, 2, 3, 4, 5)
 y <- c(0.4, 0.6, 0.2, 0.2, 0.1)
 df <- cbind(x, y)

I would like to be able to extend x to 10 and just use the last y value (0.1) to be populated all the way (i.e. in all the missing fields x = 6, 7, 8, 9, 10). Is it possible?

like image 389
liv Avatar asked Dec 23 '22 17:12

liv


1 Answers

Here is a base R idea,

rbind(df, setNames(data.frame(x = seq(6, 10), y = df$y[nrow(df)]), names(df)))

#    x   y
#1   1 0.4
#2   2 0.6
#3   3 0.2
#4   4 0.2
#5   5 0.1
#6   6 0.1
#7   7 0.1
#8   8 0.1
#9   9 0.1
#10 10 0.1
like image 171
Sotos Avatar answered May 24 '23 06:05

Sotos