[R] (no subject)

David Winsemius dwinsemius at comcast.net
Sun Oct 4 22:34:27 CEST 2015


On Oct 4, 2015, at 11:31 AM, FERNANDO MANSITO CABALLERO 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)))
>> $family$spouse
> [1] "Fred"
>> #instead of [1] "Fred" "Mary"
> 
> Where am I wrong?

The $ function is short-hand for "[[" (with an unevaluated argument). The "[[" function is not able to deliver multiple values. You might think you needed to use:

sapply( Empl[c(2,4)], function(x){ x$family$spouse )


And you cannot use that construction or its equivalent, because sapply and lapply do not pass the names of their arguments:

> sapply( Empl[c(2,4)], function(x){ x[['family']]['spouse']} )
$family
NULL

$family
NULL

#-----------


This succeeds:

> sapply( Empl[grepl('family', names(Empl)) ], function(x){x$spouse})
family family 
"Fred" "Mary" 


-- 

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list