How to save for loop results in data frame using cbind
I found solution that helped me to solve my task here: Append data frames together in a for loop
by using empty list and combining later on in data frame
datalist = list()
for (i in 1:24) {
subh= subset(dfSub$heat, dfSub$hr == i)
datalist[[i]] = subh
}
big_data = do.call(rbind, datalist)
both cbind and rbind work.
Thanks everyone for help :)
Making distinct data.frame with cbind and loop function
An option is lapply
. Loop through the columnss of 'second', and cbind
to create a new column in 'first', set the names of the list
with the names of choice. As @thelatemail mentioned (and agree totally with that), it is better not to create objects in the global env, instead keep, store, process, and write from the list
itself using tools such as lapply/sapply/vapply
lst1 <- lapply(second, function(x) cbind(first, newcol = x))
names(lst1) <- paste0("t", seq_along(lst1))
As it is a list
, we can use lapply
to loop through the list
lapply(lst1, function(x) predict(originalfunction, newx = x, matrix = TRUE))
Append data frames together in a for loop
Don't do it inside the loop. Make a list, then combine them outside the loop.
datalist = list()
for (i in 1:5) {
# ... make some data
dat <- data.frame(x = rnorm(10), y = runif(10))
dat$i <- i # maybe you want to keep track of which iteration produced it?
datalist[[i]] <- dat # add it to your list
}
big_data = do.call(rbind, datalist)
# or big_data <- dplyr::bind_rows(datalist)
# or big_data <- data.table::rbindlist(datalist)
This is a much more R-like way to do things. It can also be substantially faster, especially if you use dplyr::bind_rows
or data.table::rbindlist
for the final combining of data frames.
R - Cumulative storage of looped cbind() results and possible lapply solution to double for-loop
I was wondering if it would be an option to cbind multiple at one time instead of looping. Would any of these syntax options help?
y <– data.frame(col1=c(1:3),col2=c(4:6),col3=c(7:9))
cbind(y[,c(1:3)])
col1 col2 col3
1 1 4 7
2 2 5 8
3 3 6 9
#In R, you can use ":" to specify a range. So 1,2,3,4 is equal to 1:4.
#If you don't want number 3 in that range, you can use c(1,2,4).
#For example:
cbind(y[,c(1,3)])
col1 col3
1 1 7
2 2 8
3 3 9
How to save the for loop output as data.frame in R?
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, ])
}
how to cbind the column generated in a loop in R
There are many ways to achieve what you have described. Here is one approach that will work in many circumstances.
# start with an empty list
mydata <- list()
# run through your loop, adding each vector to the list
for(i in 1:10){
# whatever is in your loop
mydata[[i]] <- # result of this iteration of loop
}
# turn your list into a dataframe
mydf <- data.frame(mydata)
# write dataframe to a file
write.csv(mydf, file="destfile.csv")
Writing a for loop with the output as a data frame in R
As this is a learning question I will not provide the solution directly.
> values <- c(-10,0,10,100)
> for (i in seq_along(values)) {print(i)} # Checking we iterate by position
[1] 1
[1] 2
[1] 3
[1] 4
> output <- vector("double", 10)
> output # Checking the place where the output will be
[1] 0 0 0 0 0 0 0 0 0 0
> for (i in seq_along(values)) { # Testing the full code
+ output[[i]] <- rnorm(10, mean = values[[i]])
+ }
Error in output[[i]] <- rnorm(10, mean = values[[i]]) :
more elements supplied than there are to replace
As you can see the error say there are more elements to put than space (each iteration generates 10 random numbers, (in total 40) and you only have 10 spaces. Consider using a data format that allows to store several values for each iteration.
So that:
> output <- ??
> for (i in seq_along(values)) { # Testing the full code
+ output[[i]] <- rnorm(10, mean = values[[i]])
+ }
> output # Should have length 4 and each element all the 10 values you created in the loop
Related Topics
Adding a New Column Based Upon Values in Another Column Using Dplyr
Delete Rows Containing Specific Strings in R
Creating a for Loop to Subset Data on R
How to Change Y Axis Limits in Decimal Points in R
Remove Rows With All or Some Nas (Missing Values) in Data.Frame
What Specifically Are the Dangers of Eval(Parse(...))
Complete Dataframe With Missing Combinations of Values
How to Use Greek Symbols in Ggplot2
Plot Multiple Columns on the Same Graph in R
Generate List of All Possible Combinations of Elements of Vector
Divide All Columns by the Value from the 2Nd Column - Apply for All Rows
How to Get to the Next Line in the R Command Prompt Without Executing
Calculate Row Means on Subset of Columns
Change Rows into Columns in R With Values Yes/No (1/0)
Calculate Group Mean, Sum, or Other Summary Stats. and Assign Column to Original Data
How to Get a Contingency Table