在R中具有多个条件的左连接

卢卡·拉玛略(Lucca Ramalho)

我正在尝试将ID替换为其各自的值。问题在于,每个id根据上一列具有不同的值type,如下所示:

>df
  type id 
1  q1   1
2  q1   2
3  q2   1
4  q2   3
5  q3   1
6  q3   2

这是类型ID及其值:

>q1
  id value
1 1  yes
2 2  no

>q2 
   id value
1  1  one hour
2  2  two hours
3  3  more than two hours

>q3
  id value
1 1  blue
2 2  yellow

我已经尝试过这样的事情:

df <- left_join(subset(df, type %in% c("q1"), q1, by = "id"))

但这会删除其他值。

我想知道如何做one liner solution(或做某事),因为有超过20种带有类型描述的向量。

关于如何做的任何想法?

这是我期望的df:

>df
  type id value
1  q1   1 yes
2  q1   2 no
3  q2   1 one hour
4  q2   3 more than two hours
5  q3   1 blue
6  q3   2 yellow
布莱恩·斯坦普(Brian Stamper)

您可以加入多个变量。您给出的示例df实际上将为此创建一个合适的查找表:

value_lookup <- data.frame(
  type = c('q1', 'q1', 'q2', 'q2', 'q3', 'q3'),
  id = c(1, 2, 1, 3, 1, 2),
  value = c('yes', 'no', 'one hour', 'more than two hours', 'blue', 'yellow')
)

然后,您就可以同时合并typeid

df <- left_join(df, value_lookup, by = c('type', 'id'))  

通常,当我需要像这样的查找表时,我会将其存储在CSV中,而不是将其全部写在代码中,但是可以做一些适合您的事情。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章