I have created a for loop which creates a series of vectors, as follows...
(For the sake of simplicity, I have not included my full code)
for (i in vectorname){
a<-(*lots of code!*)
b<-(*lots of code...*)
c<-(*lots of code..*.)
}
I would like the loop to output these vectors in a dataframe by row. Ie row 1 would be the values in vector a, row 2 is the values from vector b...etc). Can anyone advise on how I could do this?
If relevant, I should also note that each vector will contain 11 values (so the df needs 11 columns).
Thank you!
I have created a for loop which creates a series of vectors, as follows...
(For the sake of simplicity, I have not included my full code)
for (i in vectorname){
a<-(*lots of code!*)
b<-(*lots of code...*)
c<-(*lots of code..*.)
}
I would like the loop to output these vectors in a dataframe by row. Ie row 1 would be the values in vector a, row 2 is the values from vector b...etc). Can anyone advise on how I could do this?
If relevant, I should also note that each vector will contain 11 values (so the df needs 11 columns).
Thank you!
library(tidyverse)
ITERATIONS <- 5
# create an empty dataframe
my_df <- data.frame(matrix(ncol=3,nrow=0))
names(my_df) <- c("cyl", "vs", "mpg")
my_df <- my_df %>%
mutate(
cyl = as.integer(cyl),
vs = as.logical(vs),
mpg = as.double(mpg)
)
# run for loop and bind each output as a new row
for (i in 1:ITERATIONS) {
new_row <-
mtcars %>%
sample_n(10) %>%
summarise(
cyl = max(cyl),
vs = all(is.na(vs)),
mpg = mean(mpg)
)
my_df <- bind_rows(my_df, new_row)
}
my_df
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.