R逐行将列表写入CSV [英] R write list to CSV line by line

查看:47
本文介绍了R逐行将列表写入CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有以下代码:

library(party)
dat = read.csv("data.csv", header = TRUE)

train <- dat[1:1000, ]
test <- dat[1000:1200, ]

output.tree <- cforest(t_class ~ var1 + var2,
                       data = train)

train_predict <- predict(output.tree, newdata = test, OOB=TRUE, type = "prob")

for (name in names(train_predict))
{
  p <- (train_predict[[name]][1:3])
  write.table(p, file = "result.csv",col.names = FALSE, append=TRUE)
}

我正在尝试将随机森林预测的结果写入csv文件.

I am trying to write the result of the random forest prediction to a csv file.

结果train_predict如下所示:

The result train_predict looks like the following:

当我运行上面的代码时,它仅将每行的第一列写入csv,而不是全部三列.

When I run the above code its only write the first column of each row to the csv and not all three.

如何将列表的所有三列写入文件?

How can I write all three columns of the list to the file?

R中是否还有一种方法可以在您写入csv之前清除它,以防万一其中已经有东西了?

Also is there a way in R to clear the csv before you write to it in case there is something in it already?

推荐答案

不是串行写入,而是可以转换为data.frame并立即全部写入:

Rather than write serially, you can convert to a data.frame and just write all at once:

生成与您发布的内容相似的伪造数据:

Generate fake data that looks similar to what you posted:

fakeVec <- function(dummy) t(setNames(rnorm(3), letters[1:3]))
my_list <- lapply(0:4, fakeVec)
names(my_list) <- 6000:6004

这是假数据:

$`6000`
              a          b         c
[1,] -0.2444195 -0.2189598 -1.442364

$`6001`
             a        b          c
[1,] 0.2742636 1.068294 -0.8335477

$`6002`
            a        b         c
[1,] -1.13298 1.927268 -2.123603

$`6003`
             a        b            c
[1,] 0.8260184 1.003259 -0.003590849

$`6004`
              a         b         c
[1,] -0.2025963 0.1192242 -1.121807

然后转换格式:

# crush to flat matrix
my_mat <- do.call(rbind, my_list)
# add in list names as new column
my_df <- data.frame(id = names(my_list), my_mat)

现在您有一个像这样的data.frame:

Now you have a data.frame like this:

    id          a          b            c
1 6000 -0.2444195 -0.2189598 -1.442364429
2 6001  0.2742636  1.0682937 -0.833547659
3 6002 -1.1329796  1.9272681 -2.123603334
4 6003  0.8260184  1.0032591 -0.003590849
5 6004 -0.2025963  0.1192242 -1.121807439

您可以直接将其写入文件:

Which you can just write straight to a file:

write.csv(my_df, 'my_file.csv', row.names=F)

这篇关于R逐行将列表写入CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆