通过键向量(R)获取值
这实际上对应于我的其他问题,但事情变得更加复杂。我有 data.frame 和向量:
df <- data.frame(key=c(0,3:6), value=c(0,52,26,12,1))
x <- c(3,4,3,3,5,5,6,6,6,6)
并且需要基于 x 作为键从 df 获取值:
[1] 52 26 52 52 12 12 1 1 1 1
来自 以前的答案只能给出没有重复的结果:
df[df$key %in% x,"value"]
[1] 52 26 12 1
有没有办法解决 这?
另外,我看到 hash() 可以做类似的事情:
h <- hash( keys=letters, values=1:26 )
h$a # 1
h[ "a" ]
h[[ "a" ]]
z <- rep(letters[3:5],2)
h[z] # still with NO duplicates
<hash> containing 3 key-value pair(s).
c : 3
d : 4
e : 5
但看起来像它不能返回具有以下内容的值向量:
h[[z]]
Error in h[[z]] : wrong arguments for subsetting an environment
否则,它将是完美的,以便我们可以通过使用一些“真正的”哈希概念来摆脱 data.frame 。
谢谢!
This actually corresponds to my other question but things get more complicated. I have data.frame and vector:
df <- data.frame(key=c(0,3:6), value=c(0,52,26,12,1))
x <- c(3,4,3,3,5,5,6,6,6,6)
and need to obtain values from df based on x as keys:
[1] 52 26 52 52 12 12 1 1 1 1
Solution from previous answer can only give result with NO duplicates:
df[df$key %in% x,"value"]
[1] 52 26 12 1
Is there a way to solve this?
Also, I see hash() can do things like:
h <- hash( keys=letters, values=1:26 )
h$a # 1
h[ "a" ]
h[[ "a" ]]
z <- rep(letters[3:5],2)
h[z] # still with NO duplicates
<hash> containing 3 key-value pair(s).
c : 3
d : 4
e : 5
But seems like it cannot return a vector of values with something like:
h[[z]]
Error in h[[z]] : wrong arguments for subsetting an environment
Otherwise, it would be perfect so that we can get rid of data.frame by using some 'real' hash concept.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要回答您的第一个问题:使用
match
您还应该看看命名向量
To answer your first question: Use
match
You should also have a look at Named vectors
您可以使用
match
来选择您的值:You can use
match
to select your values:我不确定这是否是最好的方法,但是
merge()
会让你到达那里:更新
关于您关于
hash()
的问题,现在可以执行以下类似操作吗?I'm not sure if this is the best way, but
merge()
will get you there:Update
Regarding your question on
hash()
, would something like the following do for now?