[英]R - Create New Column
I have the following data frame: 我有以下数据框:
X1
House-US
House-FR
FR-FR
US-US
FR-US
I would like to create a second column such that: 我想创建第二列,以便:
X1 X2
House-US House
House-FR House
FR-FR Ia
US-US Ia
FR-US Ir
If a row starts with House then X2 equal to House, If a row has left equal to right (FR-FR) then X2 equal to Ia and Else X2 equal to Ir. 如果某行以House开始,则X2等于House,如果某行的左等于右(FR-FR),则X2等于Ia,其他X2等于Ir。
Do you have a solution? 你有解决方案吗?
This works: 这有效:
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"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.