How do I repeat the last row of a data frame n times, while changing 1 or 2 variables?

Viewed 612

I have a cohort life expectancy data, which I would like to repeat the last row n times, but changing some values. I want to find a general function that can be applied to all sizes of data frames.

> df <- data.frame(Year = c(2000,2001,2002), Age = c(0,1,2), x = c(1,2,3), y = c(0.3,0.7,0.5))
> df
  Year Age x   y
1 2000   0 1 0.3
2 2001   1 2 0.7
3 2002   2 3 0.5

I want to repeat the last row, say 3 times, while increasing the value of Year and Age by 1 for every new row that I create, like this:

> df2
  Year Age x   y
1 2000   0 1 0.3
2 2001   1 2 0.7
3 2002   2 3 0.5
4 2003   3 3 0.5
5 2004   4 3 0.5
6 2005   5 3 0.5

Basically increasing the value of Year and Age but letting x and y stay constant.

4 Answers

You can repeat the last row number n times, and add the seq(n) on Age to increase it by 1, i.e.

rbind(df, transform(df[rep(nrow(df), 3),], Age = Age + seq(3), Year = Year + seq(3)))

#    Year Age x   y
#1   2000   0 1 0.3
#2   2001   1 2 0.7
#3   2002   2 3 0.5
#31  2003   3 3 0.5
#3.1 2004   4 3 0.5
#3.2 2005   5 3 0.5

The dplyr approach of @Sotos solution:

df %>% 
  bind_rows(df[rep(nrow(df), 3),] %>% 
              mutate(Age = Age + seq(3),
                     Year = Year + seq(3)))

It is a bit unclear what the use case is here so it is hard to give you a robust solution, but a quick way would be:

# your initial dataframe
df <- data.frame(Year = c(2000,2001,2002), Age = c(0,1,2), x = c(1,2,3), y = c(0.3,0.7,0.5))

# set the number you'd like to replicate
n <- 5

# create another df with similar columns (this is unnecessary as you could've done it from the beginning)
df2 <- data.frame(Year = c(2003:(2003+n)), Age = c(3:(3+n)), x = rep(3, n), y = rep(0.5, n))

# then bind the frames
final_df <- rbind(df, df2)


Does this help?

-Brennan

A slightly different approach to the other good ones posted here:

df[4:6, ] <- df[3, ]
  # make new rows numbered 4 to 6 as copies of row 3
df$Year[4:6] <- 2003:2005
  # overwrite new parts of Year variable
df$Age[4:6] <- 3:5 
  # overwrite new parts of Age variable
Related