Reputation: 942
I would like to keep selected strings in a column (A1, B2), and the rest NOT DELETE them, but replace them for NA. I have seen other posts regarding deleting the rows, or partially replacing text, but I would like to replace them with NA, and I cannot find the right command/function.
myDf <- structure(list(GeogPreferences = structure(1:4, .Label = c("A1",
"B1", "A2", "B2"), class = "factor")), .Names = "Letters", class = "data.frame", row.names = c(NA, -4L))
Not this but something like
keep[, c=("A1", "B2")]
other ways replace with gsub( "non-keep", "NA", as.character(myDf$Letter) n)
Current myDf:
Letters
1 A1
2 B1
3 A2
4 B2
Desired:
Letters
1 A1
2 NA
3 NA
4 B2
Upvotes: 0
Views: 264
Reputation: 72919
This is a job for within
.
keep <- c("A2", "B1")
within(myDf, Letters[!Letters %in% keep] <- NA)
# Letters
# 1 <NA>
# 2 B1
# 3 A2
# 4 <NA>
Upvotes: 2