[R] (no subject)
Barry Rowlingson
b.rowlingson at lancaster.ac.uk
Sun Oct 4 21:41:16 CEST 2015
lists in R can have multiple elements with the same name but if you
try and access elements by name you only get the first.
For example:
> a = list(x=99, x=23, x=456)
> a$x
[1] 99
Its just the way it is.
Note you might find the `str` function useful to see the structure of R objects:
> str(Empl)
List of 4
$ employee: chr "Anna"
$ family :List of 3
..$ spouse : chr "Fred"
..$ children : num 3
..$ child.ages: num [1:3] 4 7 9
$ employee: chr "John"
$ family :List of 3
..$ spouse : chr "Mary"
..$ children : num 2
..$ child.ages: num [1:2] 14 17
> str(Empl[c(2,4)])
List of 2
$ family:List of 3
..$ spouse : chr "Fred"
..$ children : num 3
..$ child.ages: num [1:3] 4 7 9
$ family:List of 3
..$ spouse : chr "Mary"
..$ children : num 2
..$ child.ages: num [1:2] 14 17
> str(Empl[c(2,4)]$family)
List of 3
$ spouse : chr "Fred"
$ children : num 3
$ child.ages: num [1:3] 4 7 9
With your current data structure you might need to use the
list-processing functions like `sapply` and `lapply` to get out the
spouse names from your list:
> sapply(Empl[c(2,4)], function(x){x$spouse})
family family
"Fred" "Mary"
Keep at it!
On Sun, Oct 4, 2015 at 7:31 PM, FERNANDO MANSITO CABALLERO
<fernando.mansito at gmail.com> wrote:
> Dear Madam/Sir,
>
> I am trying to understand R and I have come to a stumbling block. i
> have written:
>
>>Empl <- list(employee="Anna",family=list(spouse="Fred",children=3,
> +child.ages=c(4,7,9)),employee="John",family=list(spouse="Mary",children=2,
> +child.ages=c(14,17)))
>>Empl[c(2,4)]$family$spouse
> [1] "Fred"
>>#instead of [1] "Fred" "Mary"
>
> Where am I wrong?
>
> Thank you very much for your patience
> Yours truly,
> Fernando Mansito
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list