[R] handling the output of strsplit

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Sat Jun 21 00:30:55 CEST 2008


Denis Chabot wrote:
> Hi,
>
> Simple question, but I did not figure out how to find the answer on my
> own (wrong choice of keywords on my part).
>
> I have a character variable for time of day that has entries looking
> like "6h30", "7h40", "12h25", "23h", etc. For the sake of this
> message, say
>
> h = c("3h30",      "6h30",      "9h40",      "11h25",     "14h00",    
> "15h55",  "23h")
>
> I could not figure out how to use chron to import this into times, so
> I tried to extract the hours and minutes on my own.
>
> I used strsplit and got a list:
>
> h2 = strsplit(h, "h")
> > h2
> [[1]]
> [1] "3"  "30"
>
> [[2]]
> [1] "6"  "30"
>
> [[3]]
> [1] "9"  "40"
>
> [[4]]
> [1] "11" "25"
>
> [[5]]
> [1] "14" "00"
>
> [[6]]
> [1] "15" "55"
>
> [[7]]
> [1] "23"
>
> It is where I am stuck. I would have like to extract a vector of
> "hours" from this list, and a vector of "minutes", to reconstruct a
> time of day.
>
> But the only command I know, unlist, makes a long vector of h, min, h,
> min, h, min.
>
> For this in particular, but lists in general, how can one extract the
> first item of each element in the list, then the second item of each
> element, etc.?
>

sapply(h2, `[`, 1)
[1] "3" "6" "9" etc.

sapply(h2, `[`, 2)
[1] "30" "30" "40" etc.

? `[`

vQ



More information about the R-help mailing list