[R] Confused

(Ted Harding) ted.harding at wlandres.net
Mon Feb 7 09:57:10 CET 2011


On 07-Feb-11 08:18:49, Joel wrote:
> Hi
> Im confused by one thing, and if someone can explain it I would be a
> happy 
> 
>> rev(strsplit("hej",NULL))
> [[1]]
> [1] "h" "e" "j"
> 
>> lapply(strsplit("hej",NULL),rev)
> [[1]]
> [1] "j" "e" "h"
> 
> Why dossent the first one work? What is it in R that "fails"
> so to say that you need to use lapply for it to get the
> correct output.
> -- 

WHat's causing the confusion in your example is that the
result of strsplit("hej",NULL) consists of only one element.
This is because (see ?strsplit) the value of strsplit is
a *list*. For example, if you submit a character *vector*
(with 2 elements "hej" and "nej") to your rev(strsplit(...)):

  strsplit(c("hej","nej"),NULL)
  # [[1]]
  # [1] "h" "e" "j"
  # 
  # [[2]]
  # [1] "n" "e" "j"

  rev(strsplit(c("hej","nej"),NULL))
  # [[1]]
  # [1] "n" "e" "j"
  # 
  # [[2]]
  # [1] "h" "e" "j"

you now get a list with 2 elements [[1]]and [[2]], and rev()
now outputs these in reverse order. With your character vector
"hej" which has only one element, you get a list with only
one element, and the rev() of this is exactly the same.

Your lapply(strsplit("hej",NULL),rev) applies rev() to each
element of the list returned by strsplit, so even if it only
has one element that element gets its contents reversed.

  lapply(strsplit(c("hej","nej"),NULL),rev)
  # [[1]]
  # [1] "j" "e" "h"
  # 
  # [[2]]
  # [1] "j" "e" "n"

Hoping this helps!
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <ted.harding at wlandres.net>
Fax-to-email: +44 (0)870 094 0861
Date: 07-Feb-11                                       Time: 08:56:55
------------------------------ XFMail ------------------------------



More information about the R-help mailing list