R- Select rows with non-NA values in at least one of the four columns

无人久伴 提交于 2021-02-16 15:27:31

问题


I have this code that works fine:

CompleteCoxObs<-temp[is.na(temp[,8])== FALSE | is.na(temp[,9])== FALSE | is.na(temp[,10])== FALSE,];

What is a better and more efficient way to achieve the same result?


回答1:


You can try this to check for all the columns:

CompleteCox.df <- temp.df[rowSums(is.na(temp.df)) != ncol(temp.df),]

In your case:

CompleteCox.df <- temp.df[rowSums(is.na(temp.df[, c(8,9,10)])) != 3,]



回答2:


You can try one of the followings:

temp[!is.na(rowSums(temp[,8:10])),]

or

temp[!apply(is.na(temp[,8:10]),1,any),]

or

temp[na.omit(temp[,8:10]),]



回答3:


temp[apply(!is.na(temp[,8:10]),1,any),]

works, note placing the "!" in front of is.na



来源:https://stackoverflow.com/questions/44077122/r-select-rows-with-non-na-values-in-at-least-one-of-the-four-columns

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