繁体   English   中英

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

[英]Apply function to several variables with same name pattern

我有一个包含许多变量的data.frame ,我想将函数-log10(*htotal_pattern*)应用于具有相同名称模式htotal_一些变量。 Win_htotal_surf_eezSum_htotal_surf_LME等。

我知道R中有一个apply函数,但想知道是否可以使用变量名中的模式来完成? 正如您可以使用带list.files模式读入文件名list.files

只需使用grepl匹配您要在返回逻辑向量上进行操作的列名,即可在[运算符内部对数据框进行子集化。 因为log10是矢量化的,所以您可以执行此操作。

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

向量化的例子

#  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