Reputation: 1272
I'd like to know how I can save the output of a for loop
as data.frame
?
let's say using the mtcars
dataset I have the following for loop
script:
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:
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). I really need the loop to do what I want.
Upvotes: 4
Views: 14440
Reputation: 12559
Here is a solution that is most similar to your code.
The points are using the initialisation (indexing ...[NULL, ]
) and the function rbind()
output <- mtcars[NULL,]
for (i in seq_len(nrow(mtcars))) {
if (i <= 30) {
next
}
# ...
output <- rbind(output, mtcars[i, ])
}
Upvotes: 4