按 r 中的列计算分数

问题描述 投票:0回答:1

我有一个以主题为列的矩阵,每一行都是一个问题的答案。我需要计算每个科目的分数,我想创建一个循环。因此,对于每个人说“一点也不”的次数,它乘以 0,对于几天,它乘以 1,依此类推,然后将其相加以计算抑郁得分(总和)。它看起来像这样:

Person1       Person2        Person3
Not at all    Several days   Not at all
Several days  Several days   Several days
...

我试过:

scores1<-matrix(nrow=1,ncol=43)
x0<-1
seq<-as.vector(seq(x0,43,1))
seq<-paste0("V",seq)
colnames(scores1)=seq

for(x in colnames(t_dep_base)){
  a<-sum(str_count("Not at all"))*0
  b<-sum(str_count("Several days"))*1
  c<-sum(str_count("More than half the days"))*2
  d<-sum(str_count("Nearly every day"))*3
  suma_x<-a+b+c+d
  scores1[,suma_x]=seq
}

但是它说下标超出了范围。我很想有这样的东西:

Person1       Person2        Person3
4             0              1
r loops custom-function
1个回答
0
投票

也许是这样的:

# generating sample data:
values = c(
  "Not at all",
  "Several days",
  "More than half the days",
  "Nearly every day"
)

data = data.frame(
  Person1 = sample(values, size = 6, replace = T),
  Person2 = sample(values, size = 6, replace = T),
  Person3 = sample(values, size = 6, replace = T)
)

解决方案:

mapping <- function(x){
  switch(x,
         "Not at all" = 0,
         "Several days" = 1,
         "More than half the days" = 2,
         "Nearly every day" = 3)
}

apply(data, 2, function(z){
  sum(sapply(z, mapping))
})
© www.soinside.com 2019 - 2024. All rights reserved.