Write a Data.Table as a csv file

醉酒当歌 提交于 2019-12-11 15:43:00

问题


I have a data.table that has list values within the columns. Below is the dput:

dput(df2)

structure(list(a = list(structure(5594.05118603497, .Names = "a"), 
structure(8877.42723091876, .Names = "a"), structure(2948.95666065332, 
.Names = "a"), 
structure(5312.77623937465, .Names = "a"), structure(676.637044992807, 
.Names = "a"), 
structure(323.104243007498, .Names = "a")), b = 
list(structure(3.90258318853593e-06, .Names = "b"), 
structure(3.89772483584672e-06, .Names = "b"), structure(3.91175458242421e- 
06, .Names = "b"), 
structure(3.90169532031545e-06, .Names = "b"), structure(6.54536728417568e- 
06, .Names = "b"), 
structure(6.59087917747312e-06, .Names = "b")), id = 1:6), .Names = c("a", 
"b", "id"), class = c("data.table", "data.frame"), row.names = c(NA, 
-6L), .internal.selfref = <pointer: 0x0000000000220788>)

Here is what the output looks like:

head(df2)

          a            b id
1: 5594.051 3.902583e-06  1
2: 8877.427 3.897725e-06  2
3: 2948.957 3.911755e-06  3
4: 5312.776 3.901695e-06  4
5:  676.637 6.545367e-06  5
6: 323.1042 6.590879e-06  6

This looks ok when you see it at first but if you look further into it, this is what it looks like when I want to select a column:

How do I change df2 to just be a normal dataframe where it doesn't have these extra values within a and b like this? I am trying to write this file to a csv but it will not allow me to because it is saying there are vectors as the values.

Thanks!

Edit:

This was the code that generated the lists:

test<-sapply(  split( df , df$ID), 
function(d){ dat <- list2env(d)
nlsfit <- nls( form = y ~ a * (1-exp(-b * x)), data=dat, 
start= list( a=max(dat$y), b=b.start),
           control= control1) 

list(a = coef(nlsfit)[1], b = coef(nlsfit)[2])} )
df1<-as.data.frame(t(test))

回答1:


Load the right package, look at its help page, search for "csv", follow the Usage section:

library(data.table)
help(pac=data.table)
fwrite(df2, file="~/test.csv") # for mac, need changing for other OS

Another approach might be:

 as.data.frame( lapply(df2, unlist) )


来源:https://stackoverflow.com/questions/52730383/write-a-data-table-as-a-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!