问题
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