Reputation: 1274
I'm trying to replace a long vector values such as:
I tried the following but it doesn't give the expected output:
set.seed(1)
x=sample(c(1,2,3,4,5,6,7,8,9),size=15,replace=TRUE)
print("step1")
x
as.numeric(gsub(c(1,2,3), 1, x))
as.numeric(gsub(c(6,7,8), 2, x))
as.numeric(gsub(c(4,5,9), 3, x))
print("step2")
x
I obtained the following:
[1] "step1"
3 4 6 9 2 9 9 6 6 1 2 2 7 4 7
Warning message in gsub(c(1, 2, 3), 1, x):
"l'argument pattern a une longueur > 1 et seul le premier élément est utilisé"
3 4 6 9 2 9 9 6 6 1 2 2 7 4 7
Warning message in gsub(c(6, 7, 8), 2, x):
"l'argument pattern a une longueur > 1 et seul le premier élément est utilisé"
3 4 2 9 2 9 9 2 2 1 2 2 7 4 7
Warning message in gsub(c(4, 5, 9), 3, x):
"l'argument pattern a une longueur > 1 et seul le premier élément est utilisé"
3 3 6 9 2 9 9 6 6 1 2 2 7 3 7
[1] "step2"
3 4 6 9 2 9 9 6 6 1 2 2 7 4 7
To be more exact, I'm wanting to replace a set of values like {6,7,8}
in a vector x with one specific value like 2
.
I hope my question is clear, I tried solutions from similar questions but I didn't obtain the expected output.
Upvotes: 2
Views: 99
Reputation: 39595
Try this replacing scheme. The vector xori
has the original values whereas x
has been changed with different conditions. Additionally, the shortcut 1:3
is equivalent to c(1,2,3)
. Here the code:
#Code
set.seed(1)
x=sample(c(1,2,3,4,5,6,7,8,9),size=15,replace=TRUE)
xori <- x
#Replace
x[x %in% 1:3]<-1
x[x %in% 6:8]<-2
x[x %in% c(4,5,9)]<-3
#Print
xori
x
Output:
xori
[1] 9 4 7 1 2 7 2 3 1 5 5 6 7 9 5
x
[1] 3 3 2 1 1 2 1 1 1 3 3 2 2 3 3
If one way is required:
#One way
x <- ifelse(x %in% 1:3,1,
ifelse(x %in% 6:8,2,
ifelse(x %in% c(4,5,9),3,NA)))
Output:
x
[1] 3 3 2 1 1 2 1 1 1 3 3 2 2 3 3
Upvotes: 1
Reputation: 887088
An option with case_when
library(dplyr)
case_when(x %in% 1:3 ~ 1, x %in% 6:8 ~ 2, x %in% c(4, 5, 9) ~ 3)
#[1] 3 3 2 1 1 2 1 1 1 3 3 2 2 3 3
set.seed(1)
x <- sample(c(1,2,3,4,5,6,7,8,9),size=15,replace=TRUE)
Upvotes: 1