简体   繁体   English

R,拨浪鼓,重新编码

[英]R , rattle , recode

R , rattle 拨浪鼓

here is my data : 这是我的数据:

KK<- c('yes','no','yes','yes','dp')
LL<- c('dp','no','yes','yes','no')
II<- c('yes','dp','no','no','no')
JJ<- c('yes','no','yes','yes','dp')
AA<- c('no','dp','yes','yes','yes')
MYDATA <- data.frame(KK,LL,II,JJ,AA);MYDATA

Target: 目标:

recode 「no」 to 「0.0」 将“ no”重新编码为“ 0.0”

recode 「yes」to 「1.0」 将「是」重新编码为「1.0」

recode 「dp」to 「0.5」 将「dp」重新编码为「0.5」

Question: how can i recode in r with the package 「rattle」 问题:如何使用包“ rattle”在r中重新编码

Assuming that you are looking for a numeric result: 假设您正在寻找数值结果:

(MYDATA == "dp") / 2 + (MYDATA == "yes")

giving: 给予:

      KK  LL  II  JJ  AA
[1,] 1.0 0.5 1.0 1.0 0.0
[2,] 0.0 0.0 0.5 0.0 0.5
[3,] 1.0 1.0 0.0 1.0 1.0
[4,] 1.0 1.0 0.0 1.0 1.0
[5,] 0.5 0.0 0.0 0.5 1.0

We can convert the 'MYDATA' to 'matrix', change the 'character' class to 'factor' by specifying the labels to '0.5, 0, 1' based on the order of levels and assign it back to 'MYDATA'. 我们可以将“ MYDATA”转换为“矩阵”,通过根据级别顺序将标签指定为“ 0.5、0、1”,然后将“ character”类更改为“ factor”,然后将其分配回“ MYDATA”。 [] will ensure that the structure remains the same. []将确保结构保持不变。

MYDATA[] <- as.numeric(as.character(factor(as.matrix(MYDATA), 
                            labels=c(0.5, 0, 1))))

MYDATA 
#   KK  LL  II  JJ  AA
#1 1.0 0.5 1.0 1.0 0.0
#2 0.0 0.0 0.5 0.0 0.5
#3 1.0 1.0 0.0 1.0 1.0
#4 1.0 1.0 0.0 1.0 1.0
#5 0.5 0.0 0.0 0.5 1.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM