Selvam
Selvam

Reputation: 1093

Extracting value from a list by name

I have a list:

>data<- list("Apple"=12,"orange"=4,"pear"=5)
>fruit<- "Apple"

Now I extract the value for the Apple.

>data$fruit

I get NULL.

Upvotes: 0

Views: 91

Answers (1)

Roland
Roland

Reputation: 132676

data<- list("Apple"=12,"orange"=4,"pear"=5)
fruit<- "Apple"

data[fruit]
#$Apple
#[1] 12

data[[fruit]]
#[1] 12

As you see [ returns a list whereas [[ returns the vector. The former can select more than one element and the latter only a single element. You might benefit from reading ?"$".

Upvotes: 5

Related Questions