【发布时间】:2016-11-19 06:16:51
【问题描述】:
我最近开始学习 R。这是我正在使用的源文件 (https://github.com/cosname/art-r-translation/blob/master/data/Grades.txt)。无论如何我可以在不使用循环的情况下将字母等级从 A 更改为 4.0、A- 到 3.7 等?
我问是因为如果有 1M 条目,“for”循环可能不是修改数据的最有效方式。我将不胜感激。
由于其中一位发帖人告诉我发布我的代码,我想运行 for 循环来看看我是否能够做到。这是我的代码:
mygrades<-read.table("grades.txt",header = TRUE)
i <- for (i in 1:nrow(mygrades))
{
#print(i)
#for now, see whether As get replaced with 4.0.
if(mygrades[i,1]=="A")
{
mygrades[i,1]=4.0
}
else if (mygrades[i,2]=="A")
{
mygrades[i,2]=4.0
}
else if (mygrades[i,3]=="A")
{
mygrades[i,3]=4.0
}
else
{
#do nothing...continues
}
}
write.table(mygrades,"newgrades.txt")
但是,输出有点奇怪。对于某些“A”,我得到 NA,而其他人则保持原样。有人可以帮我处理这段代码吗?
@alistaire,我确实尝试了 Hadley 的查找表,它确实有效。我还查看了 dplyr 代码,它运行良好。但是,为了我的理解,我仍在尝试使用 for 循环。请注意,我打开一本 R 书已经过去了大约两天。这是修改后的代码。
#there was one mistake in my code: I didn't use stringsAsFactors=False.
#now, this code doesn't work for all "A"s. It spits out 4.0 for some As, and #doesn't do so for others. Why would that be?
mygrades<-read.table("grades.txt",header = TRUE,stringsAsFactors=FALSE)
i <- for (i in 1:nrow(mygrades))
{
#print(i)
if(mygrades[i,1]=="A")
{
mygrades[i,1]=4.0
}
else if (mygrades[i,2]=="A")
{
mygrades[i,2]=4.0
}
else if (mygrades[i,3]=="A")
{
mygrades[i,3]=4.0
}
else
{
#do nothing...continues
}
}
write.table(mygrades,"newgrades.txt")
输出是:
"final_exam" "quiz_avg" "homework_avg"
"1" "C" "4" "A"
"2" "C-" "B-" "4"
"3" "D+" "B+" "4"
"4" "B+" "B+" "4"
"5" "F" "B+" "4"
"6" "B" "A-" "4"
"7" "D+" "B+" "A-"
"8" "D" "A-" "4"
"9" "F" "B+" "4"
"10" "4" "C-" "B+"
"11" "A+" "4" "A"
"12" "A-" "4" "A"
"13" "B" "4" "A"
"14" "D-" "A-" "4"
"15" "A+" "4" "A"
"16" "B" "A-" "4"
"17" "F" "D" "A-"
"18" "B" "4" "A"
"19" "B" "B+" "4"
"20" "A+" "A-" "4"
"21" "4" "A" "A"
"22" "B" "B+" "4"
"23" "D" "B+" "4"
"24" "A-" "A-" "4"
"25" "F" "4" "A"
"26" "B+" "B+" "4"
"27" "A-" "B+" "4"
"28" "A+" "4" "A"
"29" "4" "A-" "A"
"30" "A+" "A-" "4"
"31" "4" "B+" "A-"
"32" "B+" "B+" "4"
"33" "C" "4" "A"
正如您在第一行中看到的,第一个 A 被重新编码为 4,但第二个 A 没有被重新编码。知道为什么会这样吗?
提前致谢。
【问题讨论】:
-
key <- c(A = 4, 'A-' = 3.7, F = 0); key[c('F','A','A-')] -
@rawr 你去哪儿了?它只是一个带有密钥的数据框,没有任何实际替换,对吧?
-
@rawr 您发布的代码。它什么也没做。我试图帮助你解释它的用途?
-
这是一个通用的概念,可以用于许多其他方面。这是一个:
grades <- as.matrix(read.table('https://raw.githubusercontent.com/cosname/art-r-translation/master/data/Grades.txt', header = TRUE)); un <- unique(c(grades)); key <- setNames(c(1:100, seq(un)), c(1:100, sort(un))); data.frame(matrix(key[grades], nrow(grades))) -
@Hack-R 哈哈好吧:“我从不投反对票”
标签: r data-analysis