[R] lapply, strsplit, and list elements

Dick Harray tomdharray at gmail.com
Fri Feb 4 16:37:28 CET 2011


Hi there,

I have a problem about lapply, strsplit, and accessing list elements,
which I don't understand or cannot solve:

I have e.g. a character vector with three elements:

x = c("349/077,349/074,349/100,349/117",
         "340/384.2,340/513,367/139,455/128,D13/168",
         "600/437,128/903,128/904")

	
The task I want to perform, is to generate a list, comprising the
portion in front of the "/" of each element of x:

neededResult = list(c("349","349", "349", "349"),
                             c("340", "340", "367", "455", "D13"),
                             c("600", "128", "128") )


I figured out that for a single element of x the following works

unlist( lapply( strsplit( unlist( strsplit(x[1], "\\,") ), "/"), "[", 1) )

but due to "unlist" it doesn't provide the required result if extended
to all elements of x

unlist(lapply(strsplit( unlist( lapply(x, strsplit, "\\,")), "/"), "[",))


Someone can help me to get the needed result?

Thanks and regards,

Dirk



More information about the R-help mailing list