在R中使用字典/列表:如何从键值对中获取值? [英] Working with dictionaries/lists in R: how to get the values from the key-value pairs?

查看:1733
本文介绍了在R中使用字典/列表:如何从键值对中获取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与使用R中的词典/列表有关,我们尝试创建一个带有向量的键值样式字典,但是现在介绍如何访问这些值。



我可以通过以下方式获取密钥

(12,22,33)
名称(foo)< -c(tic,$ c $)

  foo < tac,toe)
名字(foo)
[1]tictactoe

,我可以访问元素

 > lapply(FUN = function(a){foo [[a]]},X = 1:length(foo))
[[1]]
[1] 12

[[2]]
[1] 22

[[3]]
[1] 33

然后我可以做

$ $ $ $ $ $ $ $ unlist(lapply(FUN = function (a){foo [[a]]},X = 1:length(foo)))
[1] 12 22 33
#或
sapply {foo [[a]]},X = 1:length(foo))
[1] 12 22 33

但这非常不方便。我如何方便地访问 c(12,22,33)格式的值?在R中是否有一些方便的命令?

解决方案

您已经在 foo ;他们只有 名称属性,这对数据结构本身没有影响。任何期望数值向量的函数都可以很好地工作,不管名字如何。



如果你想删除名字,只需说:

  unname(foo)


This is related to Working with dictionaries/lists in R, where we try to create a key-value style dictionary with vectors, but now about how to access the values.

I can get the keys in the following way

foo <- c(12, 22, 33)
names(foo) <- c("tic", "tac", "toe")
names(foo)
[1] "tic" "tac" "toe"

and I can access the elements

> lapply(FUN=function(a){foo[[a]]},X = 1:length(foo))
[[1]]
[1] 12

[[2]]
[1] 22

[[3]]
[1] 33

and then I can do

unlist(lapply(FUN=function(a){foo[[a]]},X = 1:length(foo)))
[1] 12 22 33
#or 
sapply(FUN=function(a){foo[[a]]},X = 1:length(foo))
[1] 12 22 33

but this is very inconvenient. How can I conveniently access the values in the format c(12,22,33)? Is there some ready convenient command for this in R?

解决方案

You already have these values in foo; they only have a names attribute which has no impact on the data structure itself. Any function expecting a numeric vector will work perfectly fine, regardless of the names.

If you want to remove the names, just say:

unname(foo)

这篇关于在R中使用字典/列表:如何从键值对中获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆