如果条件是R中的向量 [英] If condition over a vector in R
本文介绍了如果条件是R中的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对R中的这种功能还很陌生.我试图做的是在向量上使用if语句.
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:
- 在此示例中如何使用多个条件?就像那些nchar(i)> 6且'mild'的元素一样,nchar(i)< 2表示还不错",依此类推.
推荐答案
在您的for语句中,i是迭代器,而不是向量的实际元素. 我认为,如果您替换以下代码,则您的代码将起作用:
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)
作者
if(nchar(id[i]) > 3)
这篇关于如果条件是R中的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文