简体   繁体   中英

How to store results from for-loop into a dataframe

I am trying to use for-loop to compute the mean difference between certain columns so when the for-loop is done, it gives a bunch of values that are the specific mean difference between certain columns. They are stored in the value section on the right side of the R studio. However, there are too many values so I really want to put all these values into a dataframe so that it is easier to read.

I have tried creating a dataframe outside of the for-loop and the magicfor library but it is still not working. Here is the pseudocode:

for (i in c(7:9,11:13, ...)){

  meannam<-paste(.....) #I tried to create a variable name for each mean

  mean_ind_diff<-mean((data[,i+1]-data[,i]),na.rm=TRUE) #computing the average of the difference between (i+1)the column and i column

  assign(meannam, mean_ind_diff) #assigning the meanname to the specific mean value)
}

the output is stored in the value section in the global environment. I can retrieve this value by calling the variable name. But I want to put all these values into a dataframe with their variable names as row name or column name.

The expected result would be a dataframe with the 'meannam' as row name(/ column name), and the mean difference values will be in the second column right next to the 'meannam'

Why not just creating a data.frame with a column as the name you gave here meannam<-paste(.....) associated with the mean difference? it would look somewhat like this:


size <- length(c(7:9,11:13, ...))

data_frame_mean_dif <- data.frame(nrow = size, ncol = 2) #in which first columns is name 
                                                         #and second column is the mean 
                                                         #difference

j <- 1 

for(i in c(7:9,11:13, ...)){

   data_frame_mean_dif[j,1] <- paste(.....)
   data_frame_mean_dif[j,2] <- mean((data[,i+1]-data[,i]),na.rm=TRUE)

   j <- j + 1

}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM