使用R中另一个数据帧的变量完成数据帧
我有一个主数据框,包含产品信息,如ID、描述和类别(以及许多其他变量)使用R中另一个数据帧的变量完成数据帧,r,dataframe,R,Dataframe,我有一个主数据框,包含产品信息,如ID、描述和类别(以及许多其他变量) main.dfTrydata.table获取更大的数据集 library(data.table) setkey(setDT(main.df), category) setDT(classes.df) main.df[classes.df][order(product.ID),] # product.ID description category classe #1: 1 abc...
main.dfTrydata.table
获取更大的数据集
library(data.table)
setkey(setDT(main.df), category)
setDT(classes.df)
main.df[classes.df][order(product.ID),]
# product.ID description category classe
#1: 1 abc... a aaa
#2: 2 bcd... b bbb
#3: 3 def... c aaa
#4: 4 efg... d ccc
#5: 5 fgh... e bbb
#6: 6 ghi... a aaa
#7: 7 hij... b bbb
#8: 8 ijk... c aaa
#9: 9 jkl... d ccc
#10: 10 klm... e bbb
或者使用dplyr
library(dplyr)
left_join(main.df, classes.df, by='category')
base R
选项将使用merge
(速度较慢)
谢谢你,阿克伦。一些注释:1)data.table方法在示例中运行良好,但在实际数据集“error in[.data.table
(main.df,classes.df):x”上总是给我一条错误消息。“serial”是一个字符列连接到i.“ID”类型的“integer”。字符列必须连接到因子或字符列;2)基本R方法工作正常,但它取消了不属于任何类别的行;3)ply方法很好:fast并将NAs添加到不属于现有类别的行类中。@Sal关于注释1),您能显示str(main.df)
和str(classes.df)吗
如果可能,您是否可以在两个数据集的一小部分上运行以检查错误是否存在。2)您可能必须在合并中使用all=TRUE
@Sal请将其粘贴到您的帖子上。从注释中读取有点困难。@Sal您在类.df中有5个变量。在示例中,您只有2个变量bles.您想将哪个变量加入itomain.df
?您是否在每个数据集的一小部分上尝试过该代码?另外,您能否dput(head(main.df))
,dput(head(classes.df))
并将输出粘贴到您的帖子中。serial
变量就是“链接”在两个数据集之间。我需要将classes.df中相应的country
添加到main.dfi中。如果我理解正确,您希望使用serial
列作为链接变量。但是,还有ID
列,这也是一个公共变量。在预期结果中,main.df
将包含多少列?
Classes ‘data.table’ and 'data.frame': 250000 obs. of 16 variables:
$ ID : int 4722 6988 9184 13224 13511 15938 19244 21162 23294 23793 ...
$ dataset : Factor w/ 2 levels "BA", "RB",..: 1 1 1 1 1 1 1 1 1 1 ...
$ prodID : num 429 429 429 429 429 429 429 429 429 429 ...
$ ProdName : chr "aaa" "aaa" "bbb" "ccc" "eee" ...
$ manufacID : num 1 1 1 1 1 1 1 1 1 1 ...
$ time : num 1271636264 1062977828 1218368958 1305424000 1284596323 ...
$ serial : chr "BA1" "BA1" "RB1" "RB7" ...
- attr(*, "sorted")= chr "serial"
- attr(*, ".internal.selfref")=<externalptr>
Classes ‘data.table’ and 'data.frame': 20565 obs. of 5 variables:
$ ID : int 652 1204 1252 1379 2334 2335 2336 2337 3186 3187 ...
$ mName : chr "XYZ" "EHD" "DLK" "TSH" ...
$ country: chr "Argentina" "USA" "UK" "Argentina" ...
$ serial : chr "RB7" "BA1" "RB97" "RB732" ...
- attr(*, ".internal.selfref")=<externalptr>
library(data.table)
setkey(setDT(main.df), category)
setDT(classes.df)
main.df[classes.df][order(product.ID),]
# product.ID description category classe
#1: 1 abc... a aaa
#2: 2 bcd... b bbb
#3: 3 def... c aaa
#4: 4 efg... d ccc
#5: 5 fgh... e bbb
#6: 6 ghi... a aaa
#7: 7 hij... b bbb
#8: 8 ijk... c aaa
#9: 9 jkl... d ccc
#10: 10 klm... e bbb
library(dplyr)
left_join(main.df, classes.df, by='category')
merge(main.df, classes.df, by='category', all.x=TRUE)