有没有办法一次重新编码多个变量? [英] Is there a way to recode multiple variables at once?
本文介绍了有没有办法一次重新编码多个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个学生成绩单分数的数据集,范围从 D- 到 A+.我想将它们重新编码为 1-12 的比例(即 D- = 1,D = 2 ... A = 11,A+ = 12).现在我正在起诉 plyr
中的 revalue
函数.我有几列要重新编码 - 是否有比在每列上运行 revalue
更短的方法?
I have a dataset of students' report card marks that range from D- to A+. I'd like to recode them into scale of 1-12 (i.e. D- = 1, D = 2 ... A = 11, A+ = 12). Right now I'm suing the revalue
function in plyr
. I have several columns that I'd like to recode - is there a shorter way to do this than running revalue
on each column?
一些数据:
student <- c("StudentA","StudentB","StudentC","StudentD","StudentE","StudentF","StudentG","StudentH","StudentI","StudentJ")
read <- c("A", "A+", "B", "B-", "A", "C", "C+", "D", "C", "B+")
write <- c("A-", "B", "C", "C+", "D", "B-", "B", "C", "D+", "B")
math <- c("C", "C", "D+", "A", "A+", "B", "B-", "C-", "D+", "C")
df <- data.frame (student, read, write, math)
现在我正在像这样重新编码它们:
Right now I'm recoding them like this:
df$read.r <- as.numeric (revalue (df$read, c("D-" = "1",
"D" = "2",
"D+" = "3",
"C-" = "4",
"C" = "5",
"C+" = "6",
"B-" = "7",
"B" = "8",
"B+" = "9",
"A-" = "10",
"A" = "11",
"A+" = "12"
)))
有没有更好的方法而不是运行 3 次(或更多)?所有列都具有相同的值.
Instead of running this 3 times (or more) is there a better way? All of the columns have identical values.
推荐答案
df1 <- df[,-1]
df1[] <- as.numeric(factor(unlist(df[,-1]),
levels=paste0(rep(LETTERS[4:1], each=3), c("-", "", "+"))))
cbind(df, setNames(df1, paste(colnames(df1), "r", sep=".")))
# student read write math read.r write.r math.r
#1 StudentA A A- C 11 10 5
#2 StudentB A+ B C 12 8 5
#3 StudentC B C D+ 8 5 3
#4 StudentD B- C+ A 7 6 11
#5 StudentE A D A+ 11 2 12
#6 StudentF C B- B 5 7 8
#7 StudentG C+ B B- 6 8 7
#8 StudentH D C C- 2 5 4
#9 StudentI C D+ D+ 5 3 3
#10 StudentJ B+ B C 9 8 5
这篇关于有没有办法一次重新编码多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文