代码之家  ›  专栏  ›  技术社区  ›  TarJae

如何向数据框中添加一行,只修改某些列

  •  2
  • TarJae  · 技术社区  · 4 年前

    为了准备绘图数据,我需要在数据中添加一个新行:

    我有这个数据框 :

    df <- data.frame(
      test_id = c(1, 1, 1, 1),
      test_nr = c(1, 1, 1, 1),
      region = c("A", "B", "C", "D"),
      test_value = c(3, 1, 1, 2)
    )
    
      test_id test_nr region test_value
    1       1       1      A          3
    2       1       1      B          1
    3       1       1      C          1
    4       1       1      D          2
    

    我想要 向该数据帧添加一行,以便 期望输出 应该是:

      test_id test_nr region test_value
    1       1       1      A       3.00
    2       1       1      B       1.00
    3       1       1      C       1.00
    4       1       1      D       2.00
    5       1       1   mean       1.75
    

    如您所见:第1列和第2列是相同的值,第3列改为“平均值”,第4列是第1-4行的平均值。

    我试过了 使用 add_row 从…起 tibble 出现错误的包:

    library(dpylr)
    library(tibble)
    
    df %>% 
      mutate(mean1 = mean(test_value)) %>% 
      add_row(test_id = test_id[1], test_nr=test_nr[1],region="mean", test_value=mean(test_value))
    
    Error in eval_tidy(xs[[j]], mask) : object 'test_id' not found
    
    2 回复  |  直到 4 年前
        1
  •  2
  •   stefan    4 年前

    你可以

    library(dplyr)
    
    df %>%
      add_row(test_id = .$test_id[1], test_nr = .$test_nr[1], region = "mean", test_value = mean(.$test_value))
    #>   test_id test_nr region test_value
    #> 1       1       1      A       3.00
    #> 2       1       1      B       1.00
    #> 3       1       1      C       1.00
    #> 4       1       1      D       2.00
    #> 5       1       1   mean       1.75
    
        2
  •  1
  •   Evan Friedland    4 年前

    使用base R方法,可以在现有行的基础上进行构建,然后 rbind 行绑定两个对象。

    # save a new vector from any row you like
    row_to_add <- df[1,] 
    
    # alter the values want one at a time
    row_to_add$region <- "mean"
    row_to_add$test_value <- mean(df$test_value)
    
    # OR alter them at once if you prefer...
    row_to_add[,c("region","test_value")] <- c("mean",mean(df$test_value))
    
    # finally use rbind to add to the bottom of the data.frame
    rbind(df,row_to_add)