[R] Recursive function calls
Rui Barradas
ruipbarradas at sapo.pt
Fri Aug 3 19:19:20 CEST 2012
Hello,
This seems to work.
trim2 <- function(x) {
if(is.atomic(x))
gsub("^[[:space:]]+|[[:space:]]+$", "", x)
else
sapply(x, function(y) trim2(y))
}
# Tests
trim2(tempobj)
trim2(tempvec)
trim2(templist)
trim2(tempdf)
# Extra test
templistlist <- list(templist, list(tempobj, tempdf))
trim2(templistlist)
Note, however, that the df is not returned as a df:
> class(trim2(tempdf))
[1] "matrix"
Hope this helps,
Rui Barradas
Em 03-08-2012 17:12, Gene Leynes escreveu:
> My apologies, I know that this is not a new problem, but I'm not sure how
> to find the answer
>
> I want to recursively loop over an object and trim trailing white space.
> When I use this function on a list of data.frame I get output like this:
> [1] "c(\" many spaces \", \" many spaces \")" "c(\" many spaces
> \", \" many spaces \")"
>
> What should I do to recombine the results?
> If anyone has a good way to search for this type of question, that would be
> appreciated. I tried rseek.org with "recursive", but after wading though
> all the rpart references I didn't find something that seemed to help with
> this problem.
>
> Thank you very much.
>
>
> trim <- function(x) {
> if(length(x)>1) sapply(x[1], trim)
> gsub("^[[:space:]]+|[[:space:]]+$", "", x)
> }
>
> tempobj = ' many spaces '
> tempvec = c(tempobj, tempobj)
> templist = list(tempvec, tempvec)
> tempdf = data.frame(x = tempvec, y = tempvec)
>
> trim(tempobj)
> trim(tempvec)
> trim(templist)
> trim(tempdf)
>
>
>
>
>
> Thank you,
> Gene Leynes
> _____________________________________________
> *Data Scientist*
> *Mobile: 312-498-7702
> **http://www.linkedin.com/in/geneleynes
> *
> <http://goog_598053156>*http://geneorama.com/ <http://geneorama.com/%20>*
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list