Skip to content
Prev 313652 / 398513 Next

A question on list and lapply

HI Bill,

bases
#$O
#[1] "Oak Harbor"

#$P
#[1] "Pensicola"
#
#$Q
#[1] "Quonset Point"

res2<- lapply(bases,function(x) {if(names(bases)[match.call()[[2]][[3]]]%in% "P") tolower(x) else paste0("(",x,")")})
res2
#$O
#[1] "(Oak Harbor)"
#
#$P
#[1] "pensicola"
#
#$Q
#[1] "(Quonset Point)"
#the names of the list elements are not lost? here, while in your solution, it is not there and needs to be named again.


res1<-lapply(seq_along(bases),
 function(i){ base <- bases[i] ; if (names(base) != "P") 
paste0("(",base,")") else tolower(base) } )
names(res1)
#NULL
?names(res2)
#[1] "O" "P" "Q"
A.K.



----- Original Message -----
From: William Dunlap <wdunlap at tibco.com>
To: arun <smartpink111 at yahoo.com>; Christofer Bogaso <bogaso.christofer at gmail.com>
Cc: R help <r-help at r-project.org>
Sent: Friday, December 14, 2012 3:59 PM
Subject: RE: [R] A question on list and lapply
match.call()[[2]][[3]], gack!

In lapply(X, FUN), FUN is applied to X[[i]], which has lost the names attribute that X
may have had.? X[i] retains a part of the names attribute (since it is a sublist of X, not an element
of X).? Hence FUN can look at the name associated with X[i] with code like the following:
? ?  lapply(seq_along(X), FUN=function(i) { Xi <- X[i] ; names(Xi) })

E.g., to apply one sort of processing to elements named "P" and another sort to those
not named "P" you can do:
? > bases <- list(O="Oak Harbor",P="Pensicola",Q="Quonset Point")
? > lapply(seq_along(bases), function(i){ base <- bases[i] ; if (names(base) != "P") paste0("(",base,")") else tolower(base) } )
? [[1]]
? [1] "(Oak Harbor)"? 
? 
? [[2]]
? [1] "pensicola"
? 
? [[3]]
? [1] "(Quonset Point)"

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com