[R] apply fn to many dataframes
Wacek Kusnierczyk
Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Tue May 26 01:27:06 CEST 2009
jim holtman wrote:
> You have to return a value from the function in the lapply and assign the
> result to another object:
>
>
>> df <- data.frame(a=1,b=2,c=3,d=4)
>> a <- list(df,df,df,df)
>> # to change the name of the second, you have to change the name and then
>>
> return
>
>> # the dataframe as the return value and assign it back into another list
>> a.1 <- lapply(a, function(x){
>>
> + names(x)[2] <- 'newName'
> + x # return
> + })
>
>> a
>>
> [[1]]
> a b c d
> 1 1 2 3 4
> [[2]]
> a b c d
> 1 1 2 3 4
> [[3]]
> a b c d
> 1 1 2 3 4
> [[4]]
> a b c d
> 1 1 2 3 4
>
>> a.1
>>
> [[1]]
> a newName c d
> 1 1 2 3 4
> [[2]]
> a newName c d
> 1 1 2 3 4
> [[3]]
> a newName c d
> 1 1 2 3 4
> [[4]]
> a newName c d
> 1 1 2 3 4
>
>
>
i think this is a typical case of where for-looping is the method of
choice, given the brief description below:
dfs = list(d1, d2, d3, d4)
for (i in 1:length(dfs))
names(dfs[[i]])[2] = 'x2'
on the side, the solution above is in the good functional style, but
seems comparatively inefficient:
dfs = replicate(1000, data.frame(a=1:1000, b=1000:1), simplify=FALSE)
library(rbenchmark)
benchmark(columns=c('test', 'elapsed'), replications=100,
'for'=for (i in 1:length(dfs))
names(dfs[[i]])[2] = 'foo',
lapply={dfs = lapply(dfs, function(df) {
names(df)[2] = 'foo'
df })})
# test elapsed
# 1 for 2.262
# 2 lapply 3.211
vQ
> On Mon, May 25, 2009 at 6:19 PM, James Fearon <jfearon at stanford.edu> wrote:
>
>
>> Hi,
>>
>> Say I have dataframes d1, d2, ... , dn, and I want to apply a function to
>> all of them. For example, say I want to change the name of the second
>> variable in each dataframe to "x2". The following doesn't work:
>>
>> a = list(d1,d2,d3,d4)
>> lapply(a,function(x) names(x)[2] = "x2")
>>
>> What would work?
>>
>> Thanks for any help.
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html<http://www.r-project.org/posting-guide.html>
>> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list