【问题标题】:combine many columns from one dataframe into another dataframe using setDT使用 setDT 将一个数据帧中的许多列组合到另一个数据帧中
【发布时间】: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


【解决方案1】:

如果我们想在单个连接中执行此操作,请创建感兴趣的列以及第二个数据的列名,然后在一次

nm1 <- c("diabetes", "hypertension", "cardiac", "hepatic")
nm2 <- paste0("i.", nm1)
setDT(df)[df1, (nm1) := mget(nm2), on = .(Serial.ID)]

-输出

df
#   Serial.ID name diabetes hypertension cardiac hepatic
#1:         1    a      yes            1       1       0
#2:         2    c       no            0       1       1
#3:         3    f      yes            0       1       0
#4:         4    h       no            0       0       1
#5:         5    u       no            1       0       0

【讨论】:

  • 非常感谢。这行得通。被赞成并被接受为解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-07
  • 2018-01-10
  • 2020-01-11
相关资源
最近更新 更多