简体   繁体   English

在R中嵌套if else语句

[英]Nested if else statement in R

I have a variables x 我有一个变量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. 如果x具有字符ds,则b = 0,否则x具有字符fg,则b = 1,否则x如果具有字符bc,则b = 2。

I have this variable in a dataset and have around 100(i have given only 4 in the example) records. 我在数据集中有这个变量,大约有100条记录(在示例中我只给出了4条)。

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 每当我们看到变量X中可用的字符串时,我只是在创建一个新的变量b。我的意思是它需要搜索我提到的变量X的每一行的字符,并根据该值为变量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 . 所以TRUE == 1FALSE == 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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