[英]Apply function to several variables with same name pattern
我有一个包含许多变量的data.frame
,我想将函数-log10(*htotal_pattern*)
应用于具有相同名称模式htotal_
一些变量。 即Win_htotal_surf_eez
, Sum_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.