简体   繁体   中英

Nested if else statement in R

I have a variables x

x <- c("adsad", "assdf", "gfdfg", "vbcvb")

If x having character ds then b =0 elseif x having character fg then b=1 elseif x having charcter bc then b=2.

I have this variable in a dataset and have around 100(i have given only 4 in the example) records.

I am just creating a new variable b whenever we see those string available in the variable X. I mean it need to search the character that i have mentioned each row of the variable X and based on that assign values to variable b

If we need to create arbitrary groups based on number of matches from the lookup then maybe we can try this:

# data
x <- c("adsad", "assdf", "gfdfg", "vbcvb", "dsXXfg", "xxdsbc", "dsfgbc")

# lookup list
lookup <- c("ds", "fg", "bc")

#result
data.frame(x = x,
           group = 
             order(
               apply(sapply(lookup, function(i) grepl(i, x) * 1), 1,
                     paste, collapse = "")
               )
           )

#        x group
# 1  adsad     2
# 2  assdf     4
# 3  gfdfg     3
# 4  vbcvb     1
# 5 dsXXfg     6
# 6 xxdsbc     5
# 7 dsfgbc     7

This should work:

b<-rep(NA,length(x))

index<-grepl("ds", x)
b[index]<-rep(0,sum(index))

index_temp<-grepl("fg", x)
index<-((index_temp)*1+(is.na(b))*1)==2
b[index]<-rep(1,sum(index))

index_temp<-grepl("bc", x)
index<-((index_temp)*1+(is.na(b))*1)==2
b[index]<-rep(2,sum(index))

Not completely convinced about the solution but you can try following:

x <- c("adsad", "assdf", "gfdfg", "vbcvb","dsfgbc","agdsfg","dsbc","fgbc")

grepl("ds",x)*1 + grepl("fg",x)*3 + grepl("bc",x)*5
[1] 1 0 3 5 9 4 6 8

While the numbers should represent each unique combination, eg

1 == ds
3 == fg
5 == bc
4 == ds & fg
6 == ds & bc
9 == ds & fg & bc
8 == fg & bc

This works because a logical vector is coerced into a numerical one if it is required. So TRUE == 1 and FALSE == 0 .

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