【发布时间】:2020-11-28 00:23:41
【问题描述】:
我想写一个function
df<-read.table( text="Serial.ID name
1 a
2 c
3 f
4 h
5 u
", sep="\t", header=T)
df1<-read.table( text="Serial.ID diabetes hypertension cardiac hepatic
1 yes 1 1 0
2 no 0 1 1
3 yes 0 1 0
4 no 0 0 1
5 no 1 0 0
", sep="\t", header=T)
require(data.table) ;require(dplyr)
intersect(names(df), names(df1))
setDT(df)[setDT(df1), diabetes := i.diabetes, on=c("Serial.ID")]
setDT(df)[setDT(df1), hypertension := i.hypertension, on=c("Serial.ID")]
setDT(df)[setDT(df1), cardiac := i.cardiac, on=c("Serial.ID")]
setDT(df)[setDT(df1), hepatic := i.hepatic, on=c("Serial.ID")]
#############################################################################
# I tried this code but it doesn't work
var<-c("diabetes","hypertension", "cardiac","hepatic" )
x<-function(
setDT(df)[setDT(df1), var := i.var, on=c("Serial.ID")]
)
我熟悉使用带有单个变量的先前函数,我不想在这里使用merge 或join。
提前致谢。
【问题讨论】:
-
您能在问题中检查您的
df和df1吗?他们都只有 1 列。 -
如果我直接使用
setDT(df)[setDT(df1), on = 'Serial.ID'],我不会得到任何i.列。 -
@RonakShah 非常感谢。这也有效。赞成。
标签: r dataframe join combinations