簡體   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