【问题标题】:Print a data.frame to a file when one of the data.frame elements is a list in R当 data.frame 元素之一是 R 中的列表时,将 data.frame 打印到文件
【发布时间】:2014-10-28 20:04:57
【问题描述】:

我是一名试图学习 R 编程的生物学家,这是我关于 stackoverflow 的第一个问题。我一直试图找到这个问题的答案,但一直在死胡同。我在 R 中有一个 data.frame,其中包含两个元素。第一个元素是人类基因 id 的字符向量,第二个元素是一个包含每个基因分数的列表

head(results)
gene_id                                                            Score
1    A1BG        3.2828283, 0.2378641, NA, 3.1857143, 9.6956522, 3.0759162
2   A2BP1            0.6417112, 0.6772069, 0.8581688, 1.9923954, 1.5723270
3     A2M                 2.826087, 1.115974, 4.392523, 3.165816, 1.422764
4  A4GALT            1.5883459, 1.9366197, 5.5967742, 0.8864038, 3.1920200
5   A4GNT 7.3592233, 1.3846154, 0.6046638, 4.7267081, 0.4980926, 3.4800000
6    AAA1            0.3452148, 0.9479344, 0.8114478, 6.0000000, 1.0670927
sapply(results, class)
gene_id       Score 
"character"      "list" 

我想将此 data.frame 打印到文件中,以便文件的每一行看起来像这样:

A1BG        3.2828283, 0.2378641, NA, 3.1857143, 9.6956522, 3.0759162

我试过了,但显然没有用,因为 data.frame 中存在一个列表:

> lapply(results, write, "results.txt", append=TRUE, ncolumns=1000)
Error in cat(list(...), file, sep, fill, labels, append) : 
argument 1 (type 'list') cannot be handled by 'cat'

请注意,该列表不能强制转换为 data.frame,因为每个基因与其相关的分数不同,即有些基因有 6 个分数,有些基因有 4 个等等...

对于这个问题的任何帮助将不胜感激。

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以将 Score 列强制转换为字符串,然后使用 write.table 存储您的 data.frame:

     dat$score <- sapply(dat$score,paste,collapse=',')
    

    示例:

    dat <- 
      data.frame(id=1:3,score=I(list(1,1:2,1:3)))
    dat$score <- 
      sapply(dat$score,paste,collapse=',')
    write.table(dat,row.names=F)
    
    # "id" "score"
    #   1 "1"
    #   2 "1,2"
    #   3 "1,2,3"
    

    【讨论】:

    • 这个解决方案效果很好。非常感谢您花时间帮助我!我真的很感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2016-05-15
    • 2012-02-13
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多