问题
As the title states I'm attempting to replace all values in a given row with 0 if any variable has NA and output this using write.table. For example:
x y z
2 3 5
4 NA 1
3 2 1
to
x y z
2 3 5
0 0 0
3 2 1
At the moment my code looks like the following
myvars <- c("x", "y", "z")
newdata <- mydata[myvars]
write.table(newdata, "data.txt", col.names=FALSE, row.names=FALSE)
回答1:
complete.cases
seems appropriate here:
dat[!complete.cases(dat),] <- 0
dat
# x y z
#1 2 3 5
#2 0 0 0
#3 3 2 1
回答2:
While the answer by @thelatemail is really cool,
It won't hurt to learn one more trick.
Here is my solution:
dat[rowSums(is.na(dat))>0,]<- 0
dat
# v1 v2 v3
#1 2 3 5
#2 0 0 0
#3 3 2 1
来源:https://stackoverflow.com/questions/31151445/replace-all-values-in-a-row-with-0-if-one-of-the-variables-has-missing-data