Execute command for each column of a data.frame

3

Hello, I have a data.frame (df) 8 rows x 8 columns. I'm calling the columns of "ST [i]".

df <- structure(list(ST1 = c(58.69, 58.5, 58.5, 58.69, 58.69, 
58.5, 58.69, 58.69), ST2 = c(68.7, 68.42, 68.42, 68.7, 
68.7, 68.42, 68.7, 68.7), ST3 = c(69.15, 69.15, 68.83, 
69.15, 69.15, 69.15, 69.15, 69.15), ST4 = c(78.99, 
80.29, 78.99, 77.7, 78.99, 80.29, 78.99, 77.7), ST5 = c(75.65, 
75.65, 75.65, 72.57, 71.07, 68.14, 66.7, 66.7), ST6 = c(71.35, 
71.35, 79.83, 86.38, 83.09, 87.49, 87.49, 78.76), ST7 = c(73.61, 
72.48, 78.22, 102.06, 82.33, 79.97, 112.48, 91.39), ST8 = c(77.57, 
77.57, 77.57, 77.57, 77.57, 77.57, 77.57, 79.17)), .Names = c("ST1", 
"ST2", "ST3", "ST4", "ST5", "ST6", "ST7", "ST8"), row.names = 122:129, class = "data.frame")

I need to run a waveslim::mra() command for each of these columns. The result of this command, for each column, will be a list with 12 vectors. Therefore, the final product will be 8 lists , each list with 12 vectors.

I can do, for example:

dwc_ST1 <- mra(ST1, wf = "la8", method = "dwt", J=3, boundary = "reflection"
dwc_ST2 <- mra(ST2, wf = "la8", method = "dwt", J=3, boundary = "reflection")
...
dwc_ST8 <- mra(ST8, wf = "la8", method = "dwt", J=3, boundary = "reflection")

But it would be great if it simplified that. I thought of for() , something like:

names_dwc <- as.character(rep(NA, ncol(df)))
for (k in 1:ncol(df)){
  names[k] <- paste('dwc_ST', k, sep = "")
  dwc_ST[k] <- mra(df[ ,k], wf = "la8", method = "dwt", J=3, boundary = "reflection")
  }

But it has appeared:

  

Error in ST [k]

asked by anonymous 07.11.2017 / 15:23

2 answers

6

You can do this on a line with lapply :

dwc_ST <- lapply(df, mra, wf = "la8", method = "dwt", J=3, boundary = "reflection")

The result is a list of the calculations for each column:

str(dwc_ST, max.level = 1)
List of 8
 $ ST1:List of 4
 $ ST2:List of 4
 $ ST3:List of 4
 $ ST4:List of 4
 $ ST5:List of 4
 $ ST6:List of 4
 $ ST7:List of 4
 $ ST8:List of 4

If you want to rename the list objects to dwc_ST1 , dwc_ST2 etc:

names(dwc_ST) <- paste0("dwc_", names(dwc_ST))

And if you do not want the objects in a list, but each of them separately on the desktop (which I do not recommend), just use list2env :

list2env(dwc_ST, envir = globalenv()) # mas não recomendo
    
07.11.2017 / 19:35
4

In your code, you create the object names_dwc and do not use it within for . In case names_dwc[k] <- paste('dwc_ST', k, sep = "") creates only a character vector and does not create dwc_ST objects as you thought. For this, there is the assign function, which assigns a value to a name. Here is the code below:

names_dwc <- as.character(rep(NA, ncol(df)))
for(k in 1:ncol(df)){
  names_dwc[k] <- paste('dwc_ST', k, sep = "")
  assign(names_dwc[k], mra(df[,k], wf = 'la8', method = 'dwt', J = 3, boundary = 'reflection'))
}
    
07.11.2017 / 17:55