[R] Recursive function calls
R. Michael Weylandt
michael.weylandt at gmail.com
Sat Aug 4 00:46:11 CEST 2012
On Fri, Aug 3, 2012 at 5:41 PM, Gene Leynes <gleynes at gmail.com> wrote:
> Ah yes, good point.
>
> this was easy enough to write, it doesn't lose dimensions, and there's no
> unnecessary complexity... unless you're passing in data frames, in which
> you'll have to recombine them.
>
> trim = function(x) gsub("^[[:space:]]+|[[:space:]]+$", "", x)
> trimmer = function(x){
> if(is.list(x)){
> rapply(x, trim, how='replace')
> }else{
> trim(x)
> }
> }
>
Possibly, though I suppose it's a matter of judgement, even more
straightforward to just make your input into a list and don't special
case:
trimmer <- function(x){rapply(list(x), function(x)
gsub("^[[:space:]]+|[[:space:]]+$", "", x), how = "replace")[[1]]}
Note the "[[1]]" to undo the list() call we added.
Best,
Michael
> tempobj = ' many spaces '
> tempvec = c(tempobj, tempobj)
> templist = list(tempvec, tempvec)
> tempdf = data.frame(x = tempvec, y = tempvec)
>
> trimmer(tempobj)
> trimmer(tempvec)
> trimmer(templist)
> trimmer(tempdf)
>
>
>
> Thank you,
> Gene Leynes
> _____________________________________________
> Data Scientist
> Mobile: 312-498-7702
> http://www.linkedin.com/in/geneleynes
> http://geneorama.com/
>
>
>
> On Fri, Aug 3, 2012 at 4:14 PM, R. Michael Weylandt
> <michael.weylandt at gmail.com> wrote:
>>
>> On Fri, Aug 3, 2012 at 3:36 PM, Gene Leynes <gleynes at gmail.com> wrote:
>> > Rui,
>> > Yes, that's exactly it, thanks!!
>> > I wouldn't have thought of the "is.atomic". I was going after a series
>> > of
>> > tests for dimension and is.list.
>> >
>> >
>>
>> One other helpful function that I haven't seen anyone mention this far
>> is ? rapply [= recursive apply]
>>
>> Best,
>> Michael
>
>
More information about the R-help
mailing list