![](/img/trans.png)
[英]Using R's tidyverse, what is the most efficient way to filter out data that meet conditions across multiple columns?
[英]what's the most efficient way to perform the same operation(s) on multiple data frames?
我很抱歉,如果這是重復的,我在任何地方都找不到。
說我有很多數據框,我想將所有列名稱都轉換為小寫。 最有效的方法是什么? 使用assign
and get
很簡單,但是我想知道是否有更快的方法?
如果我只有ChickWeight
和mtcars
,那么非動態操作就可以了。
names( ChickWeight ) <- tolower( names( ChickWeight ) )
names( mtcars ) <- tolower( names( mtcars ) )
..然后這就是我如何使此過程動態化,但是我想知道是否有更有效的解決方案?
# column headers contain uppercase
head(ChickWeight)
# start with a vector of data frame names..
# this might contain many, many data frames
tl <- c( 'ChickWeight' , 'mtcars' )
# loop through each data frame name..
for ( i in tl ){
# save it to a temporary object name
x <- get( i )
# main operations here..
# perform the operation(s) you want to run on each data frame
names( x ) <- tolower( names( x ) )
# ..end of main operations
# assign the updated data frame to overwrite the original data frame
assign( i , x )
}
# no longer contains uppercase
head(ChickWeight)
我認為您不會通過更改方法來獲得很大的提高。 一種更慣用的方式是將所有數據幀存儲在列表中,並使用類似`
dlist <- list(mtcars,ChickWeight)
(要么)
namevec <- c("mtcars","ChickWeight")
dlist <- lapply(namevec,get)
然后:
dlist <- lapply(dlist,function(x) setNames(x,tolower(names(x))))
...但是,當然要使用此方法,您必須承諾將數據框稱為列表元素,這反過來又會影響分析的整個結構。 如果您不想這樣做,那么我認為沒有什么比您的get
/ assign
方法更好的了。
如果要將列表的值分配回全局環境,可以執行以下操作:
invisible(mapply(assign,namevec,dlist,MoreArgs=list(envir=.GlobalEnv)))
我想強調的是,這不一定比原始文章中介紹的簡單方法更快或更透明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.