[英]How to save the for loop output as data.frame in R?
I'd like to know how I can save the output of a for loop
as data.frame
? 我想知道如何将for loop
的输出保存为data.frame
? let's say using the mtcars
dataset I have the following for loop
script: 让我们说使用mtcars
数据集我有以下for loop
脚本:
for (i in seq_len(nrow(mtcars))) {
if (i <= 30) {
next
}
print(mtcars[i,])
}
mpg cyl disp hp drat wt qsec vs am gear carb
Maserati Bora 15 8 301 335 3.54 3.57 14.6 0 1 5 8
mpg cyl disp hp drat wt qsec vs am gear carb
Volvo 142E 21.4 4 121 109 4.11 2.78 18.6 1 1 4 2
but if I am going to save
it in output
file as dataframe
I will get the following: 但如果我save
其作为dataframe
save
在output
文件中,我将得到以下内容:
output <- as.data.frame(c())
for (i in seq_len(nrow(mtcars))) {
if (i <= 30) {
next
}
output<- c(output,mtcars[i,])
}
### then the output is
> output
$mpg
[1] 15
$cyl
[1] 8
$disp
[1] 301
$hp
[1] 335
$drat
[1] 3.54
$wt
[1] 3.57
$qsec
[1] 14.6
$vs
[1] 0
$am
[1] 1
$gear
[1] 5
$carb
[1] 8
$mpg
[1] 21.4
$cyl
[1] 4
$disp
[1] 121
$hp
[1] 109
$drat
[1] 4.11
$wt
[1] 2.78
$qsec
[1] 18.6
$vs
[1] 1
$am
[1] 1
$gear
[1] 4
$carb
[1] 2
I know the simple indexing output <- mtcars[-(1:30), ]
, but this is not a solution for my real life situation (which is more complex). 我知道简单的索引output <- mtcars[-(1:30), ]
,但这不是我现实生活情况的解决方案(更复杂)。 I really need the loop to do what I want. 我真的需要循环来做我想要的。
Here is a solution that is most similar to your code. 这是一个与您的代码最相似的解决方案。
The points are using the initialisation (indexing ...[NULL, ]
) and the function rbind()
这些点使用初始化(索引...[NULL, ]
)和函数rbind()
output <- mtcars[NULL,]
for (i in seq_len(nrow(mtcars))) {
if (i <= 30) {
next
}
# ...
output <- rbind(output, mtcars[i, ])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.