我有分成三个小组的多个问题的数据。我想在这样的矩阵中总结中位数
numQuestions <- c("FB3Q1", "FB3Q3q1", "FB3Q3q2", "FB3Q5", "FB3Q6", "FB3Q7", "FB3Q9", "FB3Q11q1", "FB3Q11q2")
medians <- matrix(nrow = length(numQuestions), ncol = 3,
dimnames = list(numQuestions, c("Group 1", "Group 2", "Group 3")))
for(i in rownames(medians)){
for(j in c(1:3)){
medians[i,j] <- median(paste0("results",j,"$",i))
}
}
i
是问题的ID,j
是问题的组。
但是,与其计算中位数,不如编写矩阵:
Group 1 Group 2 Group 3
FB3Q1 "results1$FB3Q1" "results2$FB3Q1" "results3$FB3Q1"
FB3Q3q1 "results1$FB3Q3q1" "results2$FB3Q3q1" "results3$FB3Q3q1"
FB3Q3q2 "results1$FB3Q3q2" "results2$FB3Q3q2" "results3$FB3Q3q2"
FB3Q5 "results1$FB3Q5" "results2$FB3Q5" "results3$FB3Q5"
FB3Q6 "results1$FB3Q6" "results2$FB3Q6" "results3$FB3Q6"
FB3Q7 "results1$FB3Q7" "results2$FB3Q7" "results3$FB3Q7"
FB3Q9 "results1$FB3Q9" "results2$FB3Q9" "results3$FB3Q9"
FB3Q11q1 "results1$FB3Q11q1" "results2$FB3Q11q1" "results3$FB3Q11q1"
FB3Q11q2 "results1$FB3Q11q2" "results2$FB3Q11q2" "results3$FB3Q11q2"
很明显,我缺少一个函数来命令从paste0()
调用中得到的字符串,但是我仍然找不到它的含义。
答案 0 :(得分:0)
也许您可以尝试下面的代码
sapply(
setNames(list(results1, results2, results3), c("Group 1", "Group 2", "Group 3")),
function(v) miscTools::colMedians(v[numQuestions], na.rm = TRUE)
)
答案 1 :(得分:0)
我不是R方面的专家,但是我认为使用字符串来调用对象不是理想的选择。更好的方法是将3个results
对象组合在一起-也许要做results = list(results1, results2, results3)
-然后将循环更改为:
for(i in rownames(medians)){
for(j in c(1:3)){
medians[i,j] <- median(results[[j]][[i]])}}