简体   繁体   中英

Assign new a variable to a value in R

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")
         )

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

data

 set.seed(24)
 hg <- sample(0:14, 20, replace=TRUE)

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

不确定这是否有帮助,但是在第二行中,应该使用ifelse(hg == 6), "C",来检查hg值是否为6

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM