如何将数据从控制台写入具有列标题的.csv文件

时间:2019-01-21 20:20:37

标签: r

我正在使用R进行一些计算,以得出R2值,直线斜率,平均和标准偏差。这些数据显示在控制台中,但我需要将它们写入csv。文件带有列标题,以便我可以使用此csv。文件进行进一步分析。

我的代码示例如下:

`summary(lm(variable1~variable2, dataset))$r.squared`

 `Dataset %>%
  do({
  mod = lm(Variable1 ~ Variable2, data = .)
  data.frame(Slope = coef(mod)[2])`

我试图命名这些名称(例如S1 =(lm(variable1〜variable2,数据集))$ r.squared),然后使用它使用write.csv()和write.tbl将数据写入到csv文件中但我无法弄清楚如何在其他值下方的正确列标题下获取数据。我对R有点陌生。

enter image description here

这完全有帮助吗?控制台中的数据就是我要写入文件的数据。

1 个答案:

答案 0 :(得分:1)

使用扫帚软件包将stdout()替换为输出文件名。下面我们使用内置数据框BOD

library(broom)

fm <- lm(demand ~ Time, BOD)

write.csv(glance(fm), stdout(), row.names = FALSE)
## "r.squared","adj.r.squared","sigma","statistic","p.value","df","logLik","AIC","BIC","deviance","df.residual"
## 0.644920230248548,0.556150287810685,3.08501562857815,7.2650743318886,0.0543539205107366,2,-14.0565762149087,34.1131524298174,33.4884308375016,38.0692857142857,4

write.csv(tidy(fm), stdout(), row.names = FALSE)
## "term","estimate","std.error","statistic","p.value"
## "(Intercept)",8.52142857142858,2.65894907888091,3.2048107423761,0.0327503317720233
## "Time",1.72142857142857,0.638658910594405,2.6953801831817,0.0543539205107367