用R中的字符串“Unknown”替换NA值

时间:2016-02-08 20:58:38

标签: r

我有一个包含一年中12个月的清单X.在我的数据中,我有一个Y列,其中包含以下级别:“完成”,“未完成”和“”。我想用字符串“Unknown”替换“”。

我试过了:

for (i in 1:length(X)) {
   X[[i]]$Y[which(is.na(X[[i]]$Y))] == "Unknown"
}

我收到错误:

  

“错误:意外输入”   PList15 [[I]] $ IB.Opportunity.Type [其中(is.na(PList15 [[I]] $ IB.Opportunity))]   ==“未知”

2 个答案:

答案 0 :(得分:1)

你不需要循环,你可以这样做:

# Some data with `""`
v <- 1:10
v[c(3,5,8)] <- ""
v
 [1] "1"  "2"  ""   "4"  ""   "6"  "7"  ""   "9"  "10"


v[v == ""] <- "Unknown"

 [1] "1"       "2"       "Unknown" "4"       "Unknown" "6"       "7"       "Unknown" "9"       "10"

答案 1 :(得分:1)

由于Y是一个因素,你可以这样做:

levels(X$Y)[levels(X$Y)==""] <- "unknown"