首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在dataframe中更改包含每个特性的因子的列?

如何在dataframe中更改包含每个特性的因子的列?
EN

Stack Overflow用户
提问于 2018-11-28 05:20:37
回答 1查看 70关注 0票数 0

我有一个数据集,基本上是PHQ-9问卷的答复.其中有9列包含“完全不”、“有时”、“几天”、“超过一半的时间”、“几乎每天”等因素。得分分别为0、1、1、2、3。对这9个问题的回答最终给出了27个问题中的PHQ分数。

但是,在我的数据集中,对这些问题的答复存储为:

$利息:因子w/ 5“超过半天”,.:1 4 2 2 4 5 4 4 4 5

现在,我真正想要的是另一个列,与每个特性相邻,如上面的列,其中包含相应的分值。另外,最后我想用这些因子的分数来计算结果,给出抑郁的分数。

这就是我所看到的输出:

代码语言:javascript
复制
Interest    I_Factor Pleasure        P_factor  Score 
Not at all    0      Nearly Everyday  2          2
EN

回答 1

Stack Overflow用户

发布于 2018-11-28 06:23:20

为您创建一个模拟数据文件:

代码语言:javascript
复制
df <- data.frame(id = c("001", "002", "003", "004", "005"),
             PHQ_1 = c("Not at all", "Not at all", "Sometimes", "Sometimes", "Several Days"),
             PHQ_2 = c("Sometimes", "Sometimes", "Several Days", "More than half the days", "Nearly everyday"))

使用mutate_at为您选择问卷项目,然后大量应用psych包中的recode将likert比例尺从因素更改为数字。为新列指定“名称”,它们不会替换旧列(例如下面示例中的"numeric_columns“)。

完成后,再次使用mutate计算行和并将其放入新列。

代码语言:javascript
复制
library(dplyr)
library(psych)

test <- df %>%
  mutate_at(vars(PHQ_1:PHQ_2), funs(numeric_columns = recode(., 
                                       "Not at all" = 0,
                                       "Sometimes" = 1,
                                       "Several Days" = 1,
                                       "More than half the days" = 2,
                                       "Nearly everyday" = 3))) %>%
  mutate(total = rowSums(select(., contains("numeric_columns"))))

示例输出如下所示。保留原来的列,并且您有新的数字格式的列以及调查问卷的总分。

代码语言:javascript
复制
   id        PHQ_1                   PHQ_2 PHQ_1_numeric_columns PHQ_2_numeric_columns total
1 001   Not at all               Sometimes                     0                     1     1
2 002   Not at all               Sometimes                     0                     1     1
3 003    Sometimes            Several Days                     1                     1     2
4 004    Sometimes More than half the days                     1                     2     3
5 005 Several Days         Nearly everyday                     1                     3     4
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53512621

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档