Replace all values in a row with 0 if one of the variables has missing data

无人久伴 提交于 2019-12-02 08:33:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!