[R] Extracting the first element of a list

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Wed Mar 27 01:08:38 CET 2002


Ross Darnell <r.darnell at shrs.uq.edu.au> writes:

> Perhaps some kind person might show me the way to extract the first element of a list.
> 
> The example is
> 
> tmp <- c("A", "B C","BC D")
> 
> I want the first "word" from each of these elements, i.e. "A" ,"B" ,"BC" 
> 
> strsplit(tmp," ") returns
> 
> [[1]]
> [1] "A"
> 
> [[2]]
> [1] "B" "C"
> 
> [[3]]
> [1] "BC" "D"
> 
> I have had no success in trying to extract the first element.
> 
> Of course there may be another way to get the same result.

How about

> sapply(strsplit(tmp, " "), "[", 1)
[1] "A"  "B"  "BC"


-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list