Reputation: 3
I have a vector that has empty elements and then some pieces of data in it that I can't predict the index of. I just want to delete all the empty elements and leave a vector with only the data. I can't just try to pull the indices with data because the amount of data can vary and show up at different indices (I'm extracting from a pdf).
I've tried to make a for loop that will check if an element isn't empty and then store it in a separate vector:
n <- 1
for (i in withspace) {
if (withspace[[1]][i] != "") {
wospace[n] <- withspace[[1]][i]
n <- n + 1
}
}
But I keep getting an error like this:
Error in if (withspace[[1]][i] != "") { :
missing value where TRUE/FALSE needed
In addition: Warning message:
In if (withspace[[1]][i] != "") { :
the condition has length > 1 and only the first element will be used
withspace is the matrix storing all the data points and wospace is an initialized empty vector. This is what withspace looks like:
[[1]]
[1] "City" "" "" "" "" ""
[7] "" "" "" "" "" ""
[13] "" "" "" "" "" ""
[19] "" " Province" "" "" "" ""
[25] "" "" "" "" "" ""
[31] "" "" "" " Postal"
Is there a good way to do this?
Upvotes: 0
Views: 235
Reputation: 5254
I agree with Dave2e:
withspace[[1]][withspace[[1]] != ""]
should do the trick.
A few more observations:
Your loop cycles through the vector elements of withspace[[1]]
but within the loop you treat it as index. If you want an index, you need to define the loop as for (i in 1:length(withspace[[1]]))
.
whithspace
is clearly a list or data frame. The vector of interest, however, is withspace[[1]]
. But in your loop, you loop through the top-level (list) elements. You have to set the loop as for (i in withspace[[1]])
. In this case, withspace[[1]][i]
does not make sense inside the loop. You have to address i
directly which is an copy of the according element of withspace[[1]]
.
Upvotes: 2