[R] why Vectorize conjures a list, not a vector?
Jeff Newmiller
jdnewmil at dcn.davis.CA.us
Thu Aug 15 07:21:42 CEST 2013
Vectorize is a functional version of a for loop that maps scalars to vectors or uniform length vectors to matrices, or any non-uniform vector to a list. Type the name of the function to see how it is implemented. You are giving it vectors of a variety of lengths, so you are getting a list back. You can call unlist on the result to flatten the list if that is what you want. In this case it seems overkill... list.files(pattern="\\.csv$",recursive=TRUE,full.names=TRUE) seems more practical.
---------------------------------------------------------------------------
Jeff Newmiller The ..... ..... Go Live...
DCN:<jdnewmil at dcn.davis.ca.us> Basics: ##.#. ##.#. Live Go...
Live: OO#.. Dead: OO#.. Playing
Research Engineer (Solar/Batteries O.O#. #.O#. with
/Software/Embedded Controllers) .OO#. .OO#. rocks...1k
---------------------------------------------------------------------------
Sent from my phone. Please excuse my brevity.
Zhang Weiwu <zhangweiwu at realss.com> wrote:
>
>The manual seems to suggest, with the SIMPLIFY = TRUE default option,
>Vectorize would conjure a vector if possible.
>
>Quote:
>
> SIMPLIFY: logical or character string; attempt to reduce the result to
> a vector, matrix or higher dimensional array; see the
> ‘simplify’ argument of ‘sapply’.
>
>I assume, if each run of the function results a vector of the same
>type,
>the result should be a vector as well; there is a need of list only
>when
>data are of different type.
>
>Or, given vectors of the same type, conjure vectors of the same type.
>
>But it doesn't work that way -- see below -- so what's the magic
>inside?
>
>REPRODUCE:
>
>First, to make sure each run of the function always return vector of
>the
>same time:
>
>> for (datafile in list.files(full.names=TRUE,"16b"))
>print(mode(list.files(full.names=TRUE,datafile)))
>[1] "character"
>[1] "character"
>[1] "character"
>[1] "character"
>[1] "character"
>[1] "character"
>[1] "character"
>[1] "character"
>[1] "character"
>[1] "character"
>[1] "character"
>
>
>Then, vectorize it:
>
>> datafiles <- c(Vectorize(list.files, "path")(full.names=TRUE,path =
>list.files(base_dir,full.names=TRUE)))
>> mode(datafiles)
>[1] "list"
>
>The same happened with sapply, which should generate list only if a
>vector
>is impossible -- it generated a list when every result is a vector:
>
>> mode(sapply(list.files(base_dir,full.names=TRUE), list.files))
>[1] "list"
>
>
>------------------------------------------------------------------------
>
>______________________________________________
>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