Kelsey Evans
Kelsey Evans

Reputation: 3

create a loop that fills a vector with the number of "NA" values by column

I'm trying to create a loop that fills a vector "naVals" with the number of "NA" values by column in a data frame "wb." so far I have this:

naVals <- rep(NA, 24)
for (i in 1:24){
    naVals[i] <- sum(is.na(wb$v[i]))
}  

this is not working and i can't figure out why!

naVals <- apply(wb,2,function(wb)sum(is.na(wb)))

(I know that this code does the same thing, but I'd like to do it as a loop if possible. Thanks so much!

Upvotes: 0

Views: 313

Answers (1)

anthillcode
anthillcode

Reputation: 28

As mentioned by @joran in the comments, your for loop would work if you replace wb$v[i] with wb[[i]].

In the form that you have currently posted, you have already extracted column v and are subsetting on rows rather than columns. What you want is:

naVals <- rep(NA, 24)
for (i in 1:24) {
    naVals[i] <- sum(is.na(wb[[i]]))
}

Some extra advice, though. If you want this code to be adaptable to different data frames and not so specific then I recommend the following:

naVals <- numeric()
for (i in ncol(wb)) {
    naVals[i] <- sum(is.na(wb[[i]]))
}

This way you don't have to constantly edit both the for loop and the naVals initialization. You only need to use it on a new wb.

Upvotes: 1

Related Questions