如何使用dplyr对列进行重新编码(和反转代码)变量 [英] how to recode (and reverse code) variables in columns with dplyr

查看:512
本文介绍了如何使用dplyr对列进行重新编码(和反转代码)变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在2013年最后一次使用它之后,我再次收到了R。我习惯于使用dplyr,但是我遇到了一个简单的任务问题。
我有一张表,看起来像

 参与者Q1 Q2 Q3 Q4 Q5 
1同意中立NA不同意同意
2中立同意NA NA NA

我的目标

 参与者Q1 Q2 Q3 Q4 Q5 
1 3 2 NA 1 3
2 2 1 NA NA NA

我想能够将分类值更改为第Q1:Q5列的数值,但是我看到的所有使用示例对于dplyr,recode用于行和没有列。 (我可能会在示例中缺少某些东西)。然后我想要选择列Q1和Q2并对其进行反向编码。



如果可能,我试图学习如何在dplyr中执行此操作



谢谢

解决方案

我们可以在 base R 中,而不使用任何包。创建一个名为vector('v1')的查询,循环遍历列,并使用该向量更改列中的值

  v1 < -  setNames(c(1:3,3),c(不同意,中立,同意,同意))
df1 [-1]< - lapply(df1 [ -1],function(x)if(any(!is.na(x)))v1 [x] else NA)
df1
#参与者Q1 Q2 Q3 Q4 Q5
#1 1 3 2 NA 1 3
#2 2 2 3 NA NA NA



data < h3>

  df1<  - 结构(list(Participant = 1:2,Q1 = c(agree,neutral),
Q2 = c(中性,同意),Q3 = c(NA,NA),Q4 = c(不同意,
NA),Q5 = c(Agree,NA) ),.Names = c(Participant,Q1,
Q2,Q3,Q4,Q5),class =data.frame,row.names = c NA,-2L))


I am picking up R again after last using it in 2013. I am getting used to using dplyr, but I am running into a problem with a simple task. I have a table that looks like

Participant Q1       Q2      Q3     Q4       Q5
1           agree  neutral   NA    Disagree  Agree
2           neutral agree    NA     NA       NA

My goal

   Participant Q1       Q2      Q3     Q4       Q5
    1           3       2       NA      1       3
    2           2       1       NA     NA       NA

I want to be able to change the categorical value to a numerical value for columns Q1:Q5, but all the examples that I see of using recode for dplyr work for rows and no columns. (I might be missing something in the examples). I then want to be able to pick column Q1 and Q2 and reverse code it.

I am trying to learn to do this in dplyr if possible

Thanks

解决方案

We can do this in base R without using any package. Create a lookup named vector ('v1'), loop over the columns and use that vector to change the values in the columns

v1 <- setNames(c(1:3, 3), c("Disagree", "neutral", "agree", "Agree"))
df1[-1] <- lapply(df1[-1], function(x) if(any(!is.na(x))) v1[x] else NA)
df1 
#  Participant Q1 Q2 Q3 Q4 Q5
#1           1  3  2 NA  1  3
#2           2  2  3 NA NA NA

data

df1 <- structure(list(Participant = 1:2, Q1 = c("agree", "neutral"), 
Q2 = c("neutral", "agree"), Q3 = c(NA, NA), Q4 = c("Disagree", 
NA), Q5 = c("Agree", NA)), .Names = c("Participant", "Q1", 
"Q2", "Q3", "Q4", "Q5"), class = "data.frame", row.names = c(NA, -2L))

这篇关于如何使用dplyr对列进行重新编码(和反转代码)变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆