[R] spliting strings ...

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Thu Dec 13 15:06:27 CET 2007


Monica Pisica wrote:
> Hi everyone,
>  
> I have a vector of strings, each string made up by different number of words. I want to get a new vector which has only the first word of each string in the first vector. I came up with this:
>  
> str <- c('aaa bbb', 'cc', 'd eee aa', 'mmm o n')
> str1 <- rep(1, length(str))
> for (i in 1:length(str)) {
>      str1[i] <- strsplit(str, " ")[[i]][1]
> }
>  str1
> 'aaa'   'cc'   'd'  'mmm'
>  
> Now, is there any way to do this simpler?
>   
> sapply(strsplit(str, " "), "[", 1)
[1] "aaa" "cc"  "d"   "mmm"

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list