子集列基于某些列缺少值

时间:2014-03-27 00:44:32

标签: r

我的数据集很大。我有大约2,000个变量和1,000个观测值。 我想使用其他变量为每个变量运行一个模型。 为此,我需要删除因变量不具有缺失值的变量。

我的意思是,例如,对于变量" A"我需要删除变量C和D,因为那些变量A没有的值缺失。变量" C"我可以保持变量" D"。

data <- read.table(text="
A  B  C  D
1  3  9  4
2  1  3  4
NA NA 3  5
4  2  NA NA
2  5  4  3
1  1  1  2",header=T,sep="")

我想我需要制作一个循环来遍历每个变量。

2 个答案:

答案 0 :(得分:1)

我将提供一种方法来为您选择的每个列获取可用的vadiables:

getVars <- function(data, col){
  tmp<-!sapply(data[!is.na(data[[col]]),], function(x) { any(is.na(x)) })
  names(data)[tmp & names(data) != col]
}

PS:我在手机上,所以我没有测试上面的内容,也没有机会获得良好的代码样式。

编辑:样式修复!

答案 1 :(得分:1)

我认为这可以满足您的需求:

for (i in 1:ncol(data)) {

  # filter out rows with NA's in on column 'i'
  # which is the column we currently care about 

  tmp <- data[!is.na(data[,i]),]

  # now column 'i' has no NA values, so remove other columns
  # that have NAs in them from the data frame

  tmp <- tmp[sapply(tmp, function(x) !any(is.na(x)))] 

  #run your model on 'tmp'

}

对于i的每次迭代,tmp数据框如下所示:

'data.frame':   5 obs. of  2 variables:
 $ A: int  1 2 4 2 1
 $ B: int  3 1 2 5 1

'data.frame':   5 obs. of  2 variables:
 $ A: int  1 2 4 2 1
 $ B: int  3 1 2 5 1

'data.frame':   4 obs. of  2 variables:
 $ C: int  3 3 4 1
 $ D: int  4 5 3 2

'data.frame':   5 obs. of  1 variable:
 $ D: int  4 4 5 3 2
相关问题