通过使用另一列索引到列表中,在dataframe中创建新列?
我有一个带有一列索引的数据框,以及一个将每个索引映射到一个值的列表通过使用另一列索引到列表中,在dataframe中创建新列?,r,list,indexing,R,List,Indexing,我有一个带有一列索引的数据框,以及一个将每个索引映射到一个值的列表 x <- data.frame( index = c("bob","tom","bob","harry") ) lst <- list( "bob" = 10, "tom" = 20, "harry" = 30 ) 有没有一种不使用循环的方法来实现这一点? 我还惊讶地发现,创建“x”会生成一个包含因子而不是字符串的数据帧列在循环中使用“as.character”是否是正确索引到列表中的最佳方法? R和Stackov
x <- data.frame( index = c("bob","tom","bob","harry") )
lst <- list( "bob" = 10, "tom" = 20, "harry" = 30 )
有没有一种不使用循环的方法来实现这一点?
我还惊讶地发现,创建“x”会生成一个包含因子而不是字符串的数据帧列在循环中使用“as.character”是否是正确索引到列表中的最佳方法?
R和Stackoverflow都是新手,在尝试搜索答案失败后,我发布了第一个问题。为我的新身份道歉。您可以尝试
match
x$lookup <- unlist(lst[match(x$index, names(lst))])
x
# index lookup
#1 bob 10
#2 tom 20
#3 bob 10
#4 harry 30
(注意:@JChou,OP,在我将其编辑到我的答案之前找到了此解决方案的正确形式。)
使用不同的括号和字符索引可以:
x$index <- as.character(x$index)
x$lookup <- unlist( lst[ x$index ] )
我混合了
堆栈
和匹配
x$lookup <- stack(lst)$values[match(x$index, stack(lst)[,2])]
# index lookup
#1 bob 10
#2 tom 20
#3 bob 10
#4 harry 30
x$lookup哇,你太快了,谢谢。我试着使用你的第一个想法,并试图避免使用火柴。这似乎也很有效:x$lookup我看到了。我以为我参加晚会迟到了。你删除了你的?我之前确实删除了它,然后认为它可能会提供一些选择,所以取消删除。不过我喜欢你的。cleaner@akrun我本想在答案中添加这一点,但我将把它放在这里:“繁琐的变通方法是必要的,因为因素是最糟糕的。我只发现它们对表
有用。”
x$lookup <- unlist(lst[match(x$index, names(lst))])
x
# index lookup
#1 bob 10
#2 tom 20
#3 bob 10
#4 harry 30
merge(x,stack(lst), by.x='index', by.y='ind')
x$index <- as.character(x$index)
x$lookup <- unlist( lst[ x$index ] )
x$index <- factor(x$index, levels=names(lst))
x$lookup <- unlist( lst[ x$index ] )
x$lookup <- stack(lst)$values[match(x$index, stack(lst)[,2])]
# index lookup
#1 bob 10
#2 tom 20
#3 bob 10
#4 harry 30