简体   繁体   中英

Calling a character string into object names within a function

I've currently got a very lengthy and repetitive bit of code for data normalisation and inversion ((x-min)/(max-min)*-1)+1) that I want to clean up a bit.

This is a small sample of what it currently looks like:

W3_E1_Norm_New <- W3_E1_Average%>%
  mutate(W3_E1_Norm_New = ((W3_E1_zoo-W3_E1_Min)/(W3_E1_Max-W3_E1_Min)*-1)+1)
W3_E2_Norm_New <- W3_E2_Average%>%
  mutate(W3_E2_Norm_New = ((W3_E2_zoo-W3_E2_Min)/(W3_E2_Max-W3_E2_Min)*-1)+1)
W3_E3_Norm_New <- W3_E3_Average%>%
  mutate(W3_E3_Norm_New = ((W3_E3_zoo-W3_E3_Min)/(W3_E3_Max-W3_E3_Min)*-1)+1)

Each 'W3_E1' refers to a sample ID, and at present each sample ID requires the two lines of code to be written out each time. Ideally I'd like to write a function which can call a character string (Sample_IDs) into the names of each data frame, so something like

a_Norm_New

would return

W3_E1_Norm_New

then

W3_E2_Norm_New

etc.

Is there a way to write a function that could accomplish this?

Many thanks

I don't have your data but this should work. Define a function:

my_fun <- function (x) {

  norm_new <- paste0(x,"_Norm_New")
  average <- paste0(x,"_Average")
  zoo <- paste0(x, "_zoo")
  min <- paste0(x, "_Min")
  max <- paste0(x, "_Max")

   df <- get(average) %>%
    mutate(new_norm = ((zoo - min) / (max - min) * - 1) + 1)

  assign(df, norm_new)
}

Then run a for loop:

Sample_IDs <- c("W3_E1", "W3_E2", "W3_E3")

for (i in Sample_IDs) {
  my_fun(i)
}

With data.table , it is very easy to write functions that use quoted variable names (see a blog post I wrote on the subject ).

Here, we paste the pattern of your column name everywhere with the sufx variable:

library(data.table)

normalize <- function(dt, sufx = "W3_E1"){
  df <- as.data.table(dt)
  df[, (paste0(sufx,"_Norm_New")) := (
    (get(paste0(sufx,_zoo)) - get(paste0(sufx,"_Min"))
     )/(
       get(paste0(sufx,"_Max")) - get(paste0(sufx,"_Min"))
        )*-1)+1)
}

Here the code is not easy to read because I wanted to show that this can be done in one line but you can give more readability easily.

In this solution, you use get to unquote your variable name.

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