简体   繁体   English

将函数应用于具有相同名称模式的多个变量

[英]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_ . 我有一个包含许多变量的data.frame ,我想将函数-log10(*htotal_pattern*)应用于具有相同名称模式htotal_一些变量。 Ie Win_htotal_surf_eez , Sum_htotal_surf_LME etc. Win_htotal_surf_eezSum_htotal_surf_LME等。

I know there is an apply function in R, but wondered if it could be done using patterns in variable names? 我知道R中有一个apply函数,但想知道是否可以使用变量名中的模式来完成? As you can read in file names using patterns with list.files . 正如您可以使用带list.files模式读入文件名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. 只需使用grepl匹配您要在返回逻辑向量上进行操作的列名,即可在[运算符内部对数据框进行子集化。 Because log10 is vectorised you can just do this.... 因为log10是矢量化的,所以您可以执行此操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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