简体   繁体   中英

Apply function to several variables with same name pattern

I have a data.frame with many variables, I want to apply a function -log10(*htotal_pattern*) to some of the variables with the same name pattern htotal_ . Ie Win_htotal_surf_eez , Sum_htotal_surf_LME etc.

I know there is an apply function in R, but wondered if it could be done using patterns in variable names? As you can read in file names using patterns with list.files .

Just use grepl to match the column names you want to operate on returning a logical vector, inside the [ operator to subset the dataframe. Because log10 is vectorised you can just do this....

df[ , grepl( "htotal_" , names( df ) ) ] <-  -log10( df[ , grepl( "htotal_" , names( df ) ) ] )

Vectorised example

#  Set up the data
df <- data.frame( matrix( sample( c(1,10,1000) , 16 , repl = TRUE ) , 4 , 4 ) )
names( df ) <- c("htotal_1" , "htotal_2" , "not1" , "not2" )
#  htotal_1 htotal_2 not1 not2
#1       10       10   10 1000
#2       10       10    1   10
#3     1000        1    1 1000
#4       10     1000   10 1000

df[ , grepl( "htotal_" , names( df ) ) ] <-  -log10( df[ , grepl( "htotal_" , names( df ) ) ] )

#  htotal_1 htotal_2 not1 not2
#1       -1       -1   10 1000
#2       -1       -1    1   10
#3       -3        0    1 1000
#4       -1       -3   10 1000

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