我有一个从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次(或更多),还有更好的方法吗?所有的列都有相同的值。
发布于 2014-08-14 15:16:00
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发布于 2014-08-14 15:15:09
您可以使用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) )按列进行应用。
发布于 2014-08-14 15:14:04
不是超级高效,但至少可以解决你的3x问题:
df[,2:4] <- revalue(as.matrix(df[,2:4]), c("B"=9))https://stackoverflow.com/questions/25311446
复制相似问题