How to display the names of missing variables in a row?

advertisements

I do have a problem, which I can not solve alone. Sorry I am a newbie, and I have tried many different things already. I do have a dataframe with 23 participants and 40 variables. I want to produce a new text file saying WHICH variables are missing for each participant. What I did is:

miss_val=vector(mode='list',length=num_participants)
for ( i in 1:num_participants){
  miss_val[i]=sum(is.na(data[i,]))
}

which gives me the sum of missing values for each participant. Now I want to produce one sentence for each particopant specifying which variables are missing. I have used which(is.na(data[i,]) which only gives me the positions of the different missing values--How can I get the names? I have also tried: colnames( which( is.na (data[i,]) and it does not work either.


Without a great view of what your data looks like, it is difficult to assess. However, you may try the sapply() function. This function can loop through variables in a data frame and return a list object, which is quite flexible in terms of what it stores. Here is an example that might fit your scenario:

# construct silly data.frame
temp <- data.frame("a"=1:10, "aa"=rep(1:5, 2), "b"=rnorm(10),
"c"=sample(c("good", "bad", "ugly"), 10, replace=TRUE))
# build in some missing values
temp$a[c(1,5)] <- NA
temp$b[c(3,7, 9)] <- NA
temp$c[c(2,5)] <- NA
# take a peek at the data
temp
# construct empty list to store names of missing vars
missingVars <- list()
# loop through observations
for(i in 1:nrow(temp)) {
  # subset to one row data set
  obs.row <- temp[i,]
  # fill in missing var list with names of variables that are missing
  missingVars[[paste0("obs.",i)]] <-
    names(obs.row)[unlist(sapply(obs.row, is.na))]
}

This should work given what you have described. You can then extract the names of the missing variables either by using the row number:

missingVars[[1]]

or by using the name of the list element:

missingVars[["obs.1"]]

would both extract the names of missing variables for the first observation.