1

我正在尝试将 msigdb 数据库中的数据读取到我的 R 环境中,但是我无法将其读取为我想要的格式。现在,当我读取其中的数据时,它被读取为“整数”类型,我希望它作为“字符”类型或任何其他类型读取,这样当我在数据帧/矩阵之间传输数据时,我不会得到整数值用于项目而不是构成项目名称的书面字母。

df<-read.table("msigdb.v5.2.symbols.txt", fill = TRUE)

这是我目前拥有的,但就像我说的那样,当typeof(df[1,1])我得到"integer".

总结一下:在读取包含应该是字符的列的数据后,当前行为是:typeof(df[1,1)]产生"integer"。期望的行为是:typeof(df[1,1]]产生"character"

可重现的例子:

library(dplyr)
write.table(band_instruments, "test.txt")
df <- read.table("test.txt", header = TRUE)
typeof(df[1,1])
# [1] "integer"

谢谢!

4

1 回答 1

1
df<-read.table("msigdb.v5.2.symbols.txt", fill = TRUE, stringsAsFactors = FALSE)

默认情况下,除非在*中另有说明,否则read.table读取所有列,并将字符转换为因子。当您提取一个因子的单个单元格时,它将显示为内部整数代码。charactercolClassesread.tabledata.frame

stringsAsFactors = FALSE在调用中设置read.table解决了这个问题。

*尽管有以下评论,但这是真的。read.table首先将所有列作为字符读取,然后转换它们。这是在文档中,您可以从源代码中看到它。您可以使用以下代码确认这一点:

write.table(mtcars, "mtcars.txt")
read.table("mtcars.txt", header = TRUE, quote = ".")
# Fails because it reads the decimals in the numeric data as quotes
# From the documentation: Quoting is only considered for columns read
# as character, which is all of them unless colClasses is specified
于 2018-03-18T00:21:24.657 回答