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

查看:18
本文介绍了添加基于另一列 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天全站免登陆