I want this as my desired vector
0,2,3,0,5,0,7,0,0
I used these commands but didnt succeed.
b <- c(1:9)
b
x <- replace(b,b==c(1,4,6,8,9),c(0,0,0,0,0)
x
g <- (gsub(c(1,4,6,8,9),c(0,0,0,0,0),b))
Saw this before applying these commands.
I want this as my desired vector
0,2,3,0,5,0,7,0,0
I used these commands but didnt succeed.
b <- c(1:9)
b
x <- replace(b,b==c(1,4,6,8,9),c(0,0,0,0,0)
x
g <- (gsub(c(1,4,6,8,9),c(0,0,0,0,0),b))
Saw this before applying these commands.
When we are comparing b
with the vector using ==
we are comparing elementwise so b[1]
is compared with 1, b[2]
is compared with 4 and so on. Since length(c(1,4,6,8,9))
is shorter than length(b)
those values are recycled to match the length of b
.
b == c(1,4,6,8,9)
#[1] TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
Warning message: In b == c(1, 4, 6, 8, 9) : longer object length is not a multiple of shorter object length
To compare multiple values we need %in%
b %in% c(1,4,6,8,9)
#[1] TRUE FALSE FALSE TRUE FALSE TRUE FALSE TRUE TRUE
so that we can use replace
like
replace(b,b %in% c(1,4,6,8,9),c(0, 0, 0, 0, 0))
#[1] 0 2 3 0 5 0 7 0 0
However, replace
can accept vector of positions so we can directly do
replace(b, c(1,4,6,8,9), 0)
#[1] 0 2 3 0 5 0 7 0 0