[英]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.