Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在更改1或2个变量时,如何将数据帧的最后一行重复n次?_R_Repeat - Fatal编程技术网

R 在更改1或2个变量时,如何将数据帧的最后一行重复n次?

R 在更改1或2个变量时,如何将数据帧的最后一行重复n次?,r,repeat,R,Repeat,我有一个队列预期寿命数据,我想重复最后一行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 基本上增加了Year和Age的值

我有一个队列预期寿命数据,我想重复最后一行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

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

这里的用例有点不清楚,因此很难为您提供一个可靠的解决方案,但快速的方法是:

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


#初始数据帧

df您可以将最后一行数字重复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

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

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

df[4:6,]@Sotos解决方案的
dplyr方法:

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

我认为年份也应该扩展,像这样
rbind(df,transform(df[rep(nrow(df),3),],Age=Age+seq(3),year=year+seq(3))
给我的原始数据框很长,包含很多变量。如果有大量变量,重复变量x和y n次的部分将花费太长时间。我想找到一个可以应用于所有大小数据帧的通用函数。这里的另外两个答案更适用于我的情况。不过还是要谢谢你的帮助。我明白了——不用担心!请在下面的帖子中详细说明您的“用例”,以便我们更好地提供帮助。
df %>% 
  bind_rows(df[rep(nrow(df), 3),] %>% 
              mutate(Age = Age + seq(3),
                     Year = Year + seq(3)))