R:使用键值列表将列映射到列 [英] R : Map a column to column using key-value list
本文介绍了R:使用键值列表将列映射到列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在R中,我想使用一个键值列表将一列键转换为值.它类似于:如何通过R中的字典映射列,但是我想使用列表而不是数据.框架.
In R, I want to use a key-value list to convert a column of keys to values. It's similar to: How to map a column through a dictionary in R, but I want to use a list not a data.frame.
我尝试使用列表和列来做到这一点:
I've tried to do this using list and columns:
d = list('a'=1, 'b'=2, 'c'=3)
d[c('a', 'a', 'c', 'b')] # I want this to return c(1,1,3,2) but it doesn't
但是,上面的方法返回了一个列表:
However, the above returns a list:
list('a'=1, 'a'=1, 'c'=3, 'b'=2)
推荐答案
unlist
在这种情况下是有用的功能
unlist
is a useful function in this situation
unlist(d[c('a', 'a', 'c', 'b')], use.names=FALSE)
#[1] 1 1 3 2
或另一个选项是stack
,它返回键/值"作为"data.frame"中的列.通过设置值列,我们得到
Or another option is stack
which returns the 'key/value' as columns in a 'data.frame'. By subsetting the values column, we get
stack( d[c('a', 'a', 'c', 'b')])[,1]
#[1] 1 1 3 2
这篇关于R:使用键值列表将列映射到列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文