有条件地根据另一个data.table中的条件替换一个data.table中的值

时间:2016-11-05 08:15:23

标签: r if-statement data.table

我正在尝试根据另一个data.table中的一系列条件替换data.table列中的值。例如,如果我在列中有以下值:

dt = data.table("cand"=c("Trump, Donald","Clinton, Hillary","Rubio, Marco","Pelosi, Nancy"))

我还有另一个看起来像这样的数据表:

dt.comp = data.table("cand"=c("Trump, Donald","Clinton, Hillary","Rubio, Marco","Pelosi, Nancy"), 
                     "party"=c("REP","DEM","REP","DEM"), "office"=c("Pres","Pres","Sen","House"))

我希望原始列看起来像这样:

dt.ideal=data.table("cand"=c("rep.pres","dem.pres","rep.sen","dem.house"))

我该怎么做呢?我尝试过一系列嵌套的ifelse()函数,它们是这样开始的:

dt.ideal <- ifelse(dt %in% dt.comp$cand & dt.comp$party[which(dt==dt.comp$cand)]=="DEM" & dt.comp$office[which(dt==dt.comp$cand)]=="House",
                          "dem.house.cand",

但是当我拼出所有各种条件时,我会收到一条警告:longer object length is not a multiple of shorter object length

我觉得我接近解决方案,但我无法做到。在此先感谢您的帮助!

0 个答案:

没有答案