df_total = data.frame()
for (i in 1:7){
# vector output
model <- #some processing
# add vector to a dataframe
df <- data.frame(model)
df_total <- rbind(df_total,df)
}
Again maRtin is correct but for this to work you have start with a dataframe that already has at least one column
model <- #some processing
df <- data.frame(col1=model)
for (i in 2:17)
{
model <- # some processing
nextcol <- data.frame(model)
colnames(nextcol) <- c(paste("col", i, sep="")) # rename the comlum
df <- cbind(df, nextcol)
}
Don't do it inside the loop. Make a list, then combine them outside the loop.
n = 5
datalist = list()
# or pre-allocate for slightly more efficiency
datalist = vector("list", length = n)
for (i in 1:n) {
# ... 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.
In the Coursera course, an Introduction to R Programming, this skill was tested.
They gave all the students 332 separate csv files and asked them to programmatically combined several of the files to calculate the mean value of the pollutant.
This was my solution:
# create your empty dataframe so you can append to it.
combined_df <- data.frame(Date=as.Date(character()),
Sulfate=double(),
Nitrate=double(),
ID=integer())
# for loop for the range of documents to combine
for(i in min(id): max(id)) {
# using sprintf to add on leading zeros as the file names had leading zeros
read <- read.csv(paste(getwd(),"/",directory, "/",sprintf("%03d", i),".csv", sep=""))
# in your loop, add the files that you read to the combined_df
combined_df <- rbind(combined_df, read)
}
x <- c(1:10)
# empty data frame with variables ----
df <- data.frame(x1=character(),
y1=character())
for (i in x) {
a1 <- c(x1 == paste0("The number is ",x[i]),y1 == paste0("This is another number ", x[i]))
df <- rbind(df,a1)
}
names(df) <- c("st_column","nd_column")
View(df)
"""Produce Multiple DataFrames from the unique TFs via a Groupby"""
i=0
dfs_list=[]
for i in range(i,len(df_CDL)):
df = df_CDL[i]
print(df,'Only 1 df_CDL')
dfs= []
for _, dataframe in df.groupby('TFs'):
print('What is going on here?15',dataframe)
dfs.append([dataframe])
dfs_list.append([dfs])
#Index any dataframe you want or loop through them all. Whatever..
print('Test?10', dfs[1], 'Test?20')
print('What is going on here? 1', dfs_list[5], 'What is
going on here again? 2')