【问题标题】:Replace two rows in R dataframe by one row containing their mean将 R 数据框中的两行替换为包含其平均值的一行
【发布时间】:2020-03-16 16:02:56
【问题描述】:

我想知道用仅包含这两行平均值的一行替换 R 中数据框中的两行的最佳方法是什么?

例如,假设我有一个类似这样的数据框:

index<-c("id1", "id2", "id3", "id4")
a<-c(1,2,3,4)
b<-c(5,2,9,4)
df<-data.frame(index, a,b)

我想用一行替换 id2 和 id3 行,id.average 包含 id2 ((2+3)/2) 和 id3 ((2+9)2) 的平均值,所以我想要我的数据框最终看起来像这样:

index<-c("id1", "id.average", "id4")
a<-c(1,2.5,4)
b<-c(5,5.5,4)
df<-data.frame(index, a,b)

我这样计算行的平均值:

df2<-df[c(-1)]
row.names(df2)<-df$index
average<-apply(df2[2:3,], 2, mean)

然后删除了第 2 行和第 3 行,但后来我的行顺序搞砸了(即 id4 不是第 2 行,它仍然是第 4 行 ..)并且不知道如何添加新的行 id。平均到第 2 行,在第 1 行 (id1) 和第 3 行 (id4) 之间

【问题讨论】:

    标签: r dataframe row subset average


    【解决方案1】:

    这里有一个快速函数:

    #' Replace 2 rows with 1 in a data.frame
    #'
    #' @param obj 'data.frame'
    #' @param rownum 'integer', between 1 and the number of rows in 'obj'
    #' @param func 'function', to apply to each column; this function must
    #'   accept the 'na.rm=' argument; default 'mean'
    #' @param fill if 'character' (including 'NA'), a static value to
    #'   apply to non-numeric fields (including factors); if 'function', a
    #'   function to run to programmatically determine the return value;
    #'   this function is only called when there are two unique values to
    #'   be reduced, so in the case of identical factors/strings, it is
    #'   returned without using 'fill'
    #' @param na.rm 'logical', passed directly to 'func'
    #' @return 'data.frame' with either the same number of rows (if
    #'   'rownum == nrow(obj)') or one fewer rows
    rows2mean <- function(obj, rownum, func = mean, fill = NA, na.rm = TRUE) {
      if (length(rownum) > 1L) {
        warning("'rownum' has length > 1 and only the first element will be used")
        rownum <- rownum[1]
      }
      if (rownum < 1) {
        stop("'rownum' must be positive")
      } else if (rownum > nrow(obj)) {
        stop("'rownum' must not be greater than the number of rows")
      }
      # assumption: rownum is now in [1,nrow(obj)]
      before <- if (rownum > 1) obj[seq_len(rownum - 1L),,drop = FALSE] else NULL
      middle <- obj[unique(pmin(rownum + 0:1, nrow(obj))),,drop = FALSE]
      after <- if (rownum <= nrow(obj)) obj[-seq_len(rownum + 1L),,drop = FALSE] else NULL
      middle[] <- lapply(middle, function(el) {
        if (length(el) < 2) return(el)
        if (is.numeric(el)) return(func(el, na.rm = na.rm))
        if (el[[1]] == el[[2]]) return(el[[1]])
        if (is.function(fill)) return(fill(el)) else return(fill)
      })
      do.call(rbind.data.frame, list(before, as.data.frame(middle[1,,drop = FALSE]), after))
    }
    

    它故意允许选择最后一行,实际上是无操作。

    在行动:

    a<-c(1,2,3,4)
    b<-c(5,2,9,4)
    df<-data.frame(index=as.character(seq_along(a)), a, b)
    
    rows2mean(df, 2)
    #   index   a   b
    # 1   id1 1.0 5.0
    # 2  <NA> 2.5 5.5
    # 4   id4 4.0 4.0
    
    rows2mean(df, 4)               # no-op
    #   index a b
    # 1   id1 1 5
    # 2   id2 2 2
    # 3   id3 3 9
    # 4   id4 4 4
    

    以及使用各种fill= 选项:

    rows2mean(df, 2, fill="unk")
    #   index   a   b
    # 1   id1 1.0 5.0
    # 2   unk 2.5 5.5
    # 4   id4 4.0 4.0
    
    elem1 <- function(a) a[[1]]
    rows2mean(df, 2, fill=elem1)
    #   index   a   b
    # 1   id1 1.0 5.0
    # 2   id2 2.5 5.5
    # 4   id4 4.0 4.0
    rows2mean(df, 4, fill=elem1)   # still a no-op
    #   index a b
    # 1   id1 1 5
    # 2   id2 2 2
    # 3   id3 3 9
    # 4   id4 4 4
    

    有一个轻微的副作用:如果任何非数字列是 factors,那么 fill(或其返回值)将默默地添加到因子的 levels 中。我相信这是一件好事,因为将其用作价值的意图是明确的。 (不过,我确实认为,fill= 的唯一两个实际用途是使用默认的 fill=NA,或者提供与上下文相关的值的函数。任何其他静态返回值似乎都太粗略和错误了。)

    【讨论】:

    • 写得真好!
    【解决方案2】:

    您可以执行以下操作:

    df$index = as.character(df$index)    
    df_final = rbind(df[1,],c("id.average",apply(df[2:3,2:3],2,mean)),df[4,])
    

    得到以下输出:

    > df_final
           index   a   b
    1        id1   1   5
    2 id.average 2.5 5.5
    4        id4   4   4
    

    【讨论】:

      猜你喜欢
      • 2014-08-12
      • 1970-01-01
      • 2018-09-18
      • 1970-01-01
      • 1970-01-01
      • 2014-05-19
      • 2023-03-26
      • 2013-01-13
      • 1970-01-01
      相关资源
      最近更新 更多