I have a vector like this:
x <- c(0.9,0.9,0,0,0.9,0,0.8)
I want to eliminate all the zeros and create a new vector from it, so I have created this if statement:
if (x[i] == 0) {
y <- x[-(i)]}
But I get the following error:
Error in if (x[i] == 0) { : argument is of length zero
Anyone has a solution? Thanks in advance!
We don't need a for
loop with if/else
. It can be simply done with vectorization
y <- x[x != 0]
Create the logical vector with expression x != 0
, use that to subset ( ?Extract
with square brackets) the original vector and assign the output vector to a variable with identifier 'y'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.