If condition over a vector in R

*爱你&永不变心* 提交于 2020-05-17 06:15:11

问题


I am quite new to this kind of function in R. What I am trying to do is to use the if statement over a vector.

Specifically, let's say we have a vector of characters:

id <- c('4450', '73635', '7462', '12')

What I'd like to do is to substitute those elements containing a specific number of characters with a particular term. Here what I tried so far:

 for (i in 1:length(id)) {
     if(nchar(i) > 3) {
       id[i] <- 'good' 
     }
     else id[i] <- 'bad'
 }

However, the code doesn't work and I don't understand why. Also I'd like to ask you:

  • How can use multiple conditions in this example? Like for those elements with nchar(i) > 6 susbstitute with 'mild', nchar(i) < 2 susbsitute with 'not bad' and so on.

回答1:


In your for statement, i is the iterator, not the actual element of your vector. I think your code would work if you replace :

if(nchar(i) > 3)

by

if(nchar(id[i]) > 3)



回答2:


You could use dplyr::case_when to include multiple such conditions.

temp <- nchar(id) 
id1 <- dplyr::case_when(temp > 6 ~ 'mild', 
                        temp < 2 ~ 'not bad', 
                        #default condition
                        TRUE ~ 'bad')

Or using nested ifelse

id1 <- ifelse(temp > 6, 'mild', ifelse(temp < 2, 'not bad', 'bad'))


来源:https://stackoverflow.com/questions/61078555/if-condition-over-a-vector-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!