按名称从列表中提取值

Sel*_*vam 0 r string-literals

我有一个清单:

>data<- list("Apple"=12,"orange"=4,"pear"=5)
>fruit<- "Apple"
Run Code Online (Sandbox Code Playgroud)

现在我提取Apple的价值.

>data$fruit
Run Code Online (Sandbox Code Playgroud)

我得到NULL.

Rol*_*and 5

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

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

data[[fruit]]
#[1] 12
Run Code Online (Sandbox Code Playgroud)

如您所见,[返回一个列表,然后[[返回向量.前者可以选择多个元素,后者只能选择一个元素.你可能会从阅读中受益?"$".