有没有办法一次重新编码多个变量?

时间:2014-08-14 15:06:36

标签: r plyr

我有一个学生数据集'报告卡标记范围从D-到A +。我想将它们重新编码为1-12的等级(即D- = 1,D = 2 ... A = 11,A + = 12)。现在我起诉revalue中的plyr函数。我有几个我想要重新编码的列 - 除了在每列上运行revalue之外,还有更短的方法吗?

一些数据:

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)

现在我正在这样重新编码:

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次(或更多次)是否有更好的方法?所有列都具有相同的值。

3 个答案:

答案 0 :(得分:1)

您可以使用match()。首先将所有等级放在从最差到最好的向量中

marks <- c("D-", "D", "D+", "C-", "C", "C+", "B-", "B", "B+", "A-", "A", "A+")

然后

df$read.mark <- match(df$read, marks)

要避免将其写入三次,只需将其放入函数中,或使用apply() apply(df[2:4], 2, match, marks)逐列应用<{1}}

答案 1 :(得分:1)

 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

答案 2 :(得分:0)

效率不高,但至少可以解决你的3x问题:

df[,2:4] <- revalue(as.matrix(df[,2:4]), c("B"=9))