【问题标题】:Reading data into R将数据读入 R
【发布时间】:2018-08-26 20:20:55
【问题描述】:

我正在尝试将 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"

谢谢!

【问题讨论】:

    标签: r dataframe bioinformatics large-data r-environment


    【解决方案1】:
    df<-read.table("msigdb.v5.2.symbols.txt", fill = TRUE, stringsAsFactors = FALSE)
    

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

    在对read.table 的调用中设置stringsAsFactors = FALSE 可以解决此问题。

    *尽管有下面的评论,但这是真的。 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
    

    【讨论】:

    • 直接来自文档。它首先将它们作为字符读取,然后将它们转换。甚至可以查看我的回答,我在其中描述了在这种特殊情况下它们如何成为因素
    • 之前的评论者删除了他们的评论,但我还是会留下我的回复,给不知道这种行为的其他人。
    猜你喜欢
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多