如何更改数据帧的最后一行n次,同时更改1个或2个变量?

问题描述 投票:1回答:4

我有一个队列预期寿命数据,我想将最后一行重复n次,但是更改了一些值。

> 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

我想重复最后一行,说3次,同时为我创建的每个新行将Year和Age的值增加1,如下所示:

> 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

基本上增加Year和Age的值,但让x和y保持不变。

r repeat
4个回答
4
投票

您可以将最后一行重复n次,并在[年龄]上加上seq(n)以将其增加1,即

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

1
投票

尚不清楚用例是什么,因此很难为您提供可靠的解决方案,但较快捷的方法是:

# 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)


有帮助吗?

-布伦南


1
投票

与此处发布的其他好方法略有不同的方法:

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

0
投票

@ Sotos解决方案的dplyr方法:

df %>% 
  bind_rows(df[rep(nrow(df), 3),] %>% 
              mutate(Age = Age + seq(3),
                     Year = Year + seq(3)))
© www.soinside.com 2019 - 2024. All rights reserved.