r语言 - 根据条件更改字符行值(下标分配中不允许NAs)



我有两列。

每当给定行的第一列的值为"Breast"时,我想添加另一列(test$IHC)的值。

下面的代码应该可以正常工作:

testdat$Pathology[testdat$Pathology == "Breast"] <- paste("Breast (", testdat$IHC, ")")

然而,问题是函数testdat$Pathology[testdat$Pathology == "Breast"]在向量中包含NA,这提示在第一行执行函数时出现错误:

NAs are not allowed in subscripted assignments

我发现的问题是,na.omit()不工作,因为我认为它在数据中产生一些修改:

na.omit(testdat$Pathology[testdat$Pathology == "Breast"]) <- paste("Breast (", testdat$IHC, ")")

您可以明确检查NA。还请记住在右侧包含相同的过滤器,否则向量将不匹配并且值将偏移。

testdat$Pathology[! is.na(testdat$Pathology) & testdat$Pathology == "Breast"] <- paste0("Breast (", testdat$IHC[! is.na(testdat$Pathology) & testdat$Pathology == "Breast"], ")")

您可以通过将通用表达式保存在变量中来使它更简洁:

subscripts.to.replace <- ! is.na(testdat$Pathology) & testdat$Pathology == "Breast"
testdat$Pathology[subscripts.to.replace] <- paste0("Breast (", testdat$IHC[subscripts.to.replace], ")")

最新更新