在阅读csv之后,我很难弄清楚为什么因素水平变化的顺序。当我处理数据时,我总是按照报告的模板更改级别的顺序。然后我把它写入csv文件。然后我通过read.csv再次读取该文件,其中StringasFactor = False,或StringasFactor = True,没关系,因子级别的顺序再次改变,它看起来不像我第一次设置,所以我必须设置再次使表格像模板。有任何包读取csv而不改变因子级别的顺序。我很感激。
答案 0 :(得分:2)
订购不包含在CSV中。这些级别在导入时按字母顺序排序。
> xy <- data.frame(lvl = letters[1:5], num = rnorm(5))
> levels(xy$lvl)
[1] "a" "b" "c" "d" "e"
> factor(xy$lvl, levels = c(letters[5:1]))
[1] a b c d e
Levels: e d c b a
> xy$lvl <- factor(xy$lvl, levels = c(letters[5:1]))
> levels(xy$lvl)
[1] "e" "d" "c" "b" "a"
> write.table(xy, file = "test.txt", row.names = FALSE, col.names = TRUE, sep = ";")
> read.table("test.txt", sep = ";", header = TRUE)
lvl num
1 a 0.20222642
2 b -0.09334365
3 c 0.45378860
4 d -0.32057560
5 e 0.74415174
> xy2 <- read.table("test.txt", sep = ";", header = TRUE)
> levels(xy2$lvl)
[1] "a" "b" "c" "d" "e"