我列出了所有可能性并将它们替换为另一个词,还有另一种简单的方法来编写这些代码,例如do loop?
abnormal$type1[grepl("\\(2\\)x3", abnormal$v1)] <- "T2"
abnormal$type1[grepl("\\(4\\)x3", abnormal$v1)] <- "T4"
abnormal$type1[grepl("\\(7\\)x3", abnormal$v1)] <- "T7"
abnormal$type1[grepl("\\(8\\)x3", abnormal$v1)] <- "T8"
abnormal$type1[grepl("\\(9\\)x3", abnormal$v1)] <- "T9"
abnormal$type1[grepl("\\(10\\)x3", abnormal$v1)] <- "T10"
abnormal$type1[grepl("\\(12\\)x3", abnormal$v1)] <- "T12"
abnormal$type1[grepl("\\(13\\)x3", abnormal$v1)] <- "T13"
abnormal$type1[grepl("\\(14\\)x3", abnormal$v1)] <- "T14"
abnormal$type1[grepl("\\(15\\)x3", abnormal$v1)] <- "T15"
abnormal$type1[grepl("\\(16\\)x3", abnormal$v1)] <- "T16"
abnormal$type1[grepl("\\(17\\)x3", abnormal$v1)] <- "T17"
abnormal$type1[grepl("\\(18\\)x3", abnormal$v1)] <- "T18"
abnormal$type1[grepl("\\(20\\)x3", abnormal$v1)] <- "T20"
abnormal$type1[grepl("\\(21\\)x3", abnormal$v1)] <- "T21"
abnormal$type1[grepl("\\(22\\)x3", abnormal$v1)] <- "T22"
abnormal$type1[grepl("\\(X\\)x3", abnormal$v1)] <- "TX"
答案 0 :(得分:1)
一个基本R选项是定义出现在分配/替换两侧的简单数字向量,然后使用sapply
:
v <- as.character(c(2, 4, 7:10, 12:18, 20:22, 'X'))
sapply(v, function(x) {
pattern <- paste0("\\(", x, "\\)x3")
abnormal$type1[grepl(pattern, abnormal$v1)] <<- paste0("T", x)
})