我有以下数据框:
X1
House-US
House-FR
FR-FR
US-US
FR-US
我想创建第二列,以便:
X1 X2
House-US House
House-FR House
FR-FR Ia
US-US Ia
FR-US Ir
如果一行以House开头,那么X2等于House,如果一行等于右(FR-FR)则X2等于Ia而Else X2等于Ir。
你有解决方案吗?
答案 0 :(得分:2)
这有效:
library(data.table)
setDT(dt)
splitdf <- dt[, X1] %>% strsplit("-") %>% unlist %>%
matrix(ncol = 2, byrow = T) %>% data.frame(stringsAsFactors = FALSE)
names(splitdf) <- c("L", "R")
dt$X2 <- ifelse(splitdf[, "L"] == "House", "House",
ifelse(splitdf[, "L"] == splitdf[, "R"], "Ia", "Ir"))