Sittipak.P Sittipak.P - 1 month ago 6
R Question

how to remove one data in r

In R I have some vector.

x <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0)


I want to remove only "0" in x vector, but it removes all '0' in this vector.
Example

x=x[!x %in% 0 )]


All zero in this vector had been remove in x vector

For Example in Python

x = [0,1,0,1,0,0,0,1]
x.remove(0)
x
[1, 0, 1, 0, 0, 0, 1]
x.remove(0)
x
[1, 1, 0, 0, 0, 1]

Answer

We can use match to remove the first occurrence of a particular number

x <- c(1, 0, 1, 0, 0, 0, 1)
x[-match(1, x)] 

#[1] 0 1 0 0 0 1

If you have any other number to remove in array, for example 5 in the case below,

x <- c(1, 0, 5, 5, 0, 0, 1)
x[-match(5, x)]
#[1] 1 0 5 0 0 1
Comments