Reputation: 293
Using R, I need to assign variable a
, b
...whenever a new value is returned. For example if value is between 1:5 assign it a
, if it's between 6:7 assign it b
. Here is my r code:
hg1<- ifelse((hg >= 1) & (hg <= 5), "D",
ifelse(hg = 6), "C",
ifelse((hg >= 7) & (hg <= 8),"B"),
ifelse((hg >= 9) & (hg <= 12),"A")
)
Upvotes: 0
Views: 1183
Reputation: 886998
Assuming that we need to create some objects in the global environment based on the values in a vector ('hg'). Based on the description, values ranging from 1 to 5 would be assigned to 'D', 6 as 'C', 7 to 8 would be 'B' and 9 to 12 as 'A'. If there is any value outside the range, it will be classified as 'Other'
Here, I cbind
the logical vectors created from multiple comparison and do the %*%
with sequence of 4 ie. the total number of comparison to get unique numeric index. Based on the index, we can change the group to the LETTER
group.
v1 <- c( cbind(hg %in% 1:5, hg==6, hg %in% 7:8, hg %in% 9:12) %*% seq_len(4) +1)
split
the original vector with that grouping index so that the list elements will be named with the grouping index.
lst <- split(hg, c('Other', LETTERS[4:1])[v1])
It can be used to create objects in the global environment with list2env
(not recommended though).
list2env(lst, envir=.GlobalEnv)
D
#[1] 4 3 4 3 5 4 2 2
A
#[1] 10 9 11 12 9 10 10
B
#[1] 7 7
set.seed(24)
hg <- sample(0:14, 20, replace=TRUE)
Upvotes: 1
Reputation: 1809
Not sure I understand completely.
Do you want to assign hg
to new variables a
or b
, in which case:
assign(ifelse(hg %in% 1:5, "a", "b"), hg)
Or do you want to assign characters "a"
or "b"
to hg1
, in which case:
hg1 <- ifelse(hg %in% 1:5, "a", "b")
This code assumes that hg is 1,2,3,4,5,6 or 7. If it could be otherwise, you will need to develop it a bit more.
An alternative, based on the comment:
hg_op <- c(rep("a", 5), "b", rep("c", 2), rep("d", 4)) #once at beginning
hg1 <- hg_op[hg] #as many times as you need
Upvotes: 0
Reputation: 1800
Not sure if this helps, but in the second line, it should be
ifelse(hg == 6), "C",
to check that hg
has value 6
or not.
Upvotes: 0