[英]Write to Data Frame Then to .csv file in R
I want the output of the bellow R
code be written to .csv
file.我希望将波纹管R
代码的 output 写入.csv
文件。
N <- c(15L, 20L)
SD <- c(1, 2) ^ 2
phi = c(0.2, 0.4)
## generate all combos
all_combos <- expand.grid(N = N, SD = SD, phi = phi)
## create function
fx_arima <- function(n, SD, phi) {
(arima.sim(n = n,
model=list(ar=phi, order = c(1, 1, 0)),
start.innov = 4.1,
n.start = 1,
rand.gen = function(n) rnorm(n, mean = 0, sd = SD)))[-1]
}
## find arima for all combos using Map
Map(fx_arima, all_combos[["N"]], all_combos[["SD"]], all_combos[["phi"]])
## or :
set.seed(123L)
by(all_combos, all_combos["N"],
function(DF) {
res = mapply(fx_arima, DF[["N"]], DF[["SD"]], DF[["phi"]])
colnames(res) = paste("SD", DF[["SD"]], "phi", DF[["phi"]], sep = "_")
res
})
The above R
code simulate ARIMA(1,1,0)
with varying values of N <- c(15L, 20L), SD <- c(1, 2) ^ 2, phi = c(0.2, 0.4)
.上面的R
代码模拟了ARIMA(1,1,0)
的变化值N <- c(15L, 20L), SD <- c(1, 2) ^ 2, phi = c(0.2, 0.4)
。 N=15 is printed in a matrix and N=20 is printed in another matrix all columns with column name. N=15 打印在一个矩阵中,N=20 打印在另一个矩阵中,所有列都带有列名。 I want each matrix be writen in datafram
and then written to.csv file that will be stored in my working directory.我希望将每个矩阵写入数据帧,然后写入datafram
文件,该文件将存储在我的工作目录中。
I EXPECT THIS我期待这个
v1 v2 v3 v4
1 4 3 1
2 6 3 2
3 8 3 12
4 4 4 8
5 6 4 4
6 8 4 0
7 4 5 2
8 6 5 1
9 8 5 2
10 11 12 13
11 12 13 14
8 6 5 1
9 8 5 2
10 11 12 13
11 12 13 14
I tried what was done in How to write R output with unequal length into excel but couldn't get it我尝试了如何在如何编写 R output 中完成的操作,其中长度不等到 excel但无法得到它
We could first, save the results to a list, final.result
.我们可以首先将结果保存到一个列表final.result
中。
final.result <- by(all_combos, all_combos["N"],
function(DF) {
res = mapply(fx_arima, DF[["N"]], DF[["SD"]], DF[["phi"]])
colnames(res) = paste("SD", DF[["SD"]], "phi", DF[["phi"]], sep = "_")
res
})
Because the N
group is in the name of the object and not in the column names, we can use a loop to append the N
to the begining of the column names with paste0
.因为N
组在 object 的名称中而不是在列名中,我们可以使用循环到 append 的N
到列名的paste0
。 Then we can write out with write.table
.然后我们可以用write.table
写出来。
for(i in seq_along(final.result)){
group <- names(finalresult)[i]
colnames(final.result[[i]]) <- paste0("N_",group,"_",colnames(final.result[[i]]))
write.table(final.result[[i]],sep=",",file="test.csv",append = TRUE)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.