【问题标题】:Convert R objects to csv/text files将 R 对象转换为 csv/文本文件
【发布时间】:2015-03-22 10:58:39
【问题描述】:

有没有人尝试将 R 对象转换为文本文件?我有从 Seqmeta 包创建的 R 对象,并试图将其转换为文本文件

load("variant.Rdata")
write.csv(variants, file="variants.csv")
Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) :
  cannot coerce class ""seqMeta"" to a data.frame

然后我尝试了

dump(variant, file="variant_file")
Error in FUN(X[[1L]], ...) : invalid first argument

如何将数据转换为 csv 格式?

【问题讨论】:

  • 对象variants是什么?必须提供此信息。通过在 R 会话中运行 ?write.csv 来解释函数 write.csv。另外,如果您执行str(variants),它会返回什么?这会告诉您有关该对象的信息。
  • 做一个str(variants),你会发现它与data.frame(或任何其他write.csv 可以处理的东西)相差无几。这是一个非常复杂的数据结构(一个大列表 [prbly] 以及许多嵌套列表和列表中的对象)。
  • 是的,str(variant) 看起来很复杂。那么查看此类数据的更合适的方式是什么。我的数据看起来像这样>head(variant, n=1) > $Gene1 $Gene1$scores rs1 0 $Gene1$cov 1 x 1 sparse Matrix of class "dsCMatrix" rs1 rs1 . $Gene1$n [1] 1234 $Gene1$maf rs1 0 $Gene1$sey [1] 1

标签: r rdata


【解决方案1】:

如果您需要保存通用 R 对象,您通常会使用 saveRDS(这比对单个对象使用 save 更可取)。如果文件必须是 ASCII,saveRDSsaveserialize 都有参数 ascii=TRUEserialize 产生最可读的输出。

如果您需要文件是人类可读的 ASCII 码,那么 dump 就在正确的轨道上。您需要的唯一更改是 dump 将对象的 name 作为其参数:

dump('variant', file="variant_file")

以下是随机神经网络的每个选项的输出类型示例:

> serialize(model,connection = (con<-file('nn','w')),ascii = TRUE)
NULL
> close(con)
> writeLines(readLines('nn',n=10))
A
2
197122
131840
787
13
14
3
11
2  


> dump('model',file='nn2')
> writeLines(readLines('nn2',n=20))
model <-
structure(list(n = c(11, 2, 1), nunits = 15L, nconn = c(0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 38), conn = c(0, 1, 
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 
10, 11, 0, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), nsunits = 14, 
    decay = 0.3, entropy = FALSE, softmax = FALSE, censored = FALSE, 
    value = 198533.158122471, wts = c(19.0054841585536, 2.23487502441887, 
    4.18125434527288, -6.18031807633724, 1.74046449146894, -12.6452914163319, 
    4.36482412477615, -13.8535055297175, -2.86352652003103, -8.26639784261127, 
    -12.6981294199594, 4.6795318281078, 21.4576975495026, 2.3237431117074, 
    6.11977661730472, -4.72698798667361, -0.850474104016898, 
    -13.6710933522033, 4.09687948057462, -12.53360483838, -4.62974366307091, 
    -10.2276751641509, -11.5384259593477, 0.393593676803197, 
    11.9212104035313, -23.389751188319, 20.3888183920005, -0.900624040655219, 
    1.0351758513862, -0.343608722841881, -1.66543302778472, -1.29803652137646, 
    0.242127071364901, 0.994889406131462, -2.30836053849945, 
    0.190090309268229, -0.35494347864244, -0.201148348574871), 
    convergence = 0L), .Names = c("n", "nunits", "nconn", "conn", 
"nsunits", "decay", "entropy", "softmax", "censored", "value", 
"wts", "convergence"), class = "nnet")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 2015-05-11
    • 2011-06-12
    • 1970-01-01
    相关资源
    最近更新 更多