0

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'

Mako212
  • 6,787
  • 1
  • 18
  • 37
Narutoooo
  • 15
  • 1
  • 3
  • 1
    [See here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on making an R question that folks can help with. That includes a sample of data and all necessary code. – camille Aug 15 '19 at 18:32

1 Answers1

1

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

}