按r中的列计算得分

eyh26e7m  于 2023-03-15  发布在  其他
关注(0)|答案(1)|浏览(131)

我有一个矩阵,以主题为列,每一行是一个问题的答案。我需要计算每个主题的得分,我想创建一个循环。因此,对于每个人说“一点也不”的次数,它乘以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
6jjcrrmo

6jjcrrmo1#

也许可以这样说:

# 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))
})

相关问题