这里有一个快速函数:
#' 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,或者提供与上下文相关的值的函数。任何其他静态返回值似乎都太粗略和错误了。)