我有这个循环来计算每列的平均值,这是有效的。
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&#39;似乎很容易,但我无法通过以下方式开展工作。
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)
}
错误消息显示为:
colMedians中的错误(tog [-1]):参数&#39; x&#39;必须是一个矩阵。
我在colMedians函数之前尝试将DF2格式化为矩阵,但仍然收到错误消息:
colMedians中的错误(tog [-1]):参数&#39; x&#39;必须是一个矩阵。
我不明白这里发生了什么。谢谢你的帮助!
很高兴提供示例数据和错误回溯,但尽量保持简洁明了。
答案 0 :(得分:1)
根据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)
}
答案 1 :(得分:0)
偶然发现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函数太过困惑了。