如何将for循环输出保存为R中的data.Frame? [英] How to save the for loop output as data.frame in R?
本文介绍了如何将for循环输出保存为R中的data.Frame?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
for loop
的输出另存为data.frame
?
假设使用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
但如果我将save
作为dataframe
放入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
我知道简单的索引output <- mtcars[-(1:30), ]
,但这不是针对我的实际生活情况(更复杂)的解决方案。我真的需要循环来做我想做的事情。
推荐答案
以下是与您的代码最相似的解决方案。
这些点正在使用初始化(索引...[NULL, ]
)和函数rbind()
output <- mtcars[NULL,]
for (i in seq_len(nrow(mtcars))) {
if (i <= 30) {
next
}
# ...
output <- rbind(output, mtcars[i, ])
}
这篇关于如何将for循环输出保存为R中的data.Frame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文