【问题标题】:How do I repeat the last row of a data frame n times, while changing 1 or 2 variables?如何在更改 1 或 2 个变量的同时重复数据框的最后一行 n 次?
【发布时间】:2020-05-26 14:36:54
【问题描述】:

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


    【解决方案1】:

    你可以将最后一行的编号重复n次,并在Age上加上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
    

    【讨论】:

    • 我认为年也应该扩大,像这样rbind(df, transform(df[rep(nrow(df), 3),], Age = Age + seq(3), Year = Year + seq(3)))
    【解决方案2】:

    @Sotos 解决方案的dplyr 方法:

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

    【讨论】:

      【解决方案3】:

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

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

      这有帮助吗?

      -布伦南

      【讨论】:

      • 给我的原始数据框很长,包含很多变量。如果我有大量变量,则重复变量 x 和 y n 次的部分将花费太长时间。我想找到一个可以应用于所有大小的数据帧的通用函数。这里发布的另外两个答案更适用于我的情况。不过还是谢谢你的帮助。
      • 我明白了——不用担心!请在您的以下帖子中指定您的“用例”,以便我们更好地提供帮助。
      【解决方案4】:

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

      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
      

      【讨论】:

        猜你喜欢
        • 2011-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-20
        相关资源
        最近更新 更多