基于另一列R data.table添加列 [英] Adding a column based on another column R data.table

查看:899
本文介绍了基于另一列R data.table添加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有两个数据表:

I have two data tables in R:

#install.packages("data.table")
library(data.table)
dt1 <- data.table(Num = c(1,1,1,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,4,5,5,5))
dt2 <- data.table(Num = 1:5, Letter = c('A','B','C','D','E'))

数据表基于dt2,因此它将有两列:

I want to add a column to the first data table based on dt2, so it will have two columns:

dt1 <- dt1[,Letter := "THIS WILL CONTAIN AN 'A' FOR EVERY '1', 'B' FOR EVERY '2', ETC"]

第二个数据表用作一个键,其中字母对应于另一个数据表中的哪个数字。

The second data table serves as a key for which letter corresponds to which number in another data table.

感谢。

推荐答案

setkey(dt1, Num)
setkey(dt2, Num)
dt2[dt1]
    Num Letter
 1:   1      A
 2:   1      A
 3:   1      A
 4:   2      B
 5:   2      B

这篇关于基于另一列R data.table添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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