计算循环中每列的中位数

Compute median per column in loop

我有这个循环来计算每列的平均值,这很有效。

for (i in 1:length(DF1)) {     
    tempA <- DF1[i]                                 # save column of DF1 onto temp variable 
    names(tempA) <- 'word'                          # label temp variable for inner_join function
    DF2 <- inner_join(tempA, DF0, by='word')        # match words with numeric value from look-up DF0
    tempB <- as.data.frame(t(colMeans(DF2[-1])))    # compute mean of column
    DF3<- rbind(tempB, DF3)                         # save results togther
}

该脚本使用 inner_join 的 dplyr 包。

现在我想计算中位数而不是平均值。使用 colMedians function from 'robustbase' 似乎很容易,但我无法使下面的工作正常进行。

library(robustbase)

for (i in 1:length(DF1)) {     
    tempA <- DF1[i]
    names(tempA) <- 'word'
    DF2 <- inner_join(tempA, DF0, by='word')
    tempB <- as.data.frame(t(colMedians(DF2[-1])))
    DF3<- rbind(tempB, DF3) 
}

错误信息如下:

Error in colMedians(tog[-1]) : Argument 'x' must be a matrix.

我尝试在 colMedians 函数之前将 DF2 格式化为矩阵,但仍然收到错误消息:

Error in colMedians(tog[-1]) : Argument 'x' must be a matrix.

我不明白这是怎么回事。感谢您的帮助!

很高兴提供样本数据和错误回溯,但尽量保持简洁明了。

偶然发现 this answer 这帮助我修复了如下循环:

DF3Mean <- data.frame()                         # instantiate dataframe 
DF4Median <- data.frame(                        # instantiate dataframe

for (i in 1:length(DF1)) {     
tempA <- DF1[i]                                 # save column of DF1 onto temp variable 
names(tempA) <- 'word'                          # label temp variable for inner_join function
DF2 <- inner_join(tempA, DF0, by='word')        # match words with numeric value from look-up DF0
tempMean <- as.data.frame(t(colMeans(DF2[-1]))) # compute mean of column
DF3Mean <- rbind(tempMean, DF3Mean)             # save results togther
tempMedian <- apply(DF2[ ,2:4], 2, median)      #compute mean for columns 2,3, and 4 
DF4Median <- rbind(tempMedian, DF4Median)       # save results togther
}

我想我对 colMedian 函数的想法太深了。

根据OP的评论,以下解决了问题。
我添加了对 library(dplyr).
的调用 我的贡献是 colMedians(data.matrix(DF2[-1]), na.rm = TRUE).

library(robustbase)
library(dplyr)

for (i in 1:length(DF1)) {     
    tempA <- DF1[i]
    names(tempA) <- 'word'
    DF2 <- inner_join(tempA, DF0, by='word')
    tempB <- colMedians(data.matrix(DF2[-1]), na.rm = TRUE)
    DF3 <- rbind(tempB, DF3) 
}