[英]Extract vector names conditionally in R
I'm trying to get the names of the elements in a vector with some priorities.我正在尝试获取具有某些优先级的向量中元素的名称。
If there is any element with value "integer"
, get the name of the first of such elements (in the example below, year
)如果存在任何值为"integer"
的元素,则获取第一个此类元素的名称(在下面的示例中为year
)
But if there is no element with value "integer"
, then do the same thing with any element with value "numeric"
.但是,如果没有值为"integer"
的元素,则对任何值为"numeric"
的元素执行相同的操作。
I have tried the following without success ( this is a toy example a functional answer is appreciated ):我尝试了以下但没有成功(这是一个玩具示例,功能性答案值得赞赏):
cl <- c(group = "character", degree = "numeric", year = "integer", zoo = "integer")
names(cl[cl == "integer" || cl == "numeric"])[1]
desired.output = "year"
You're close, but there are two issues with your approach so far:您已经很接近了,但是到目前为止,您的方法存在两个问题:
||
||
operator only works with one element;运算符仅适用于一个元素; since you're looking over more than one you would want |
因为您要查看的不止一个|
instead.反而。 See ?`||`
for more details.请参阅?`||`
了解更多详情。One way of doing it would be:一种方法是:
Coalesce2 <- function(x, y) if(is.na(x)) y else x
Coalesce2(cl[cl == "integer"][1], cl[cl == "numeric"][1])
NB.注意。 The only reason I've made a new coalesce function here rather than using dplyr's is that that doesn't preserve names in the way I think you want.我在这里创建了一个新的合并 function 而不是使用 dplyr 的唯一原因是它不会以我认为你想要的方式保留名称。
As it is a fixed match, we can use %in%
由于它是固定匹配,我们可以使用%in%
names(sort(cl[cl %in% c('integer', 'numeric')]))[1]
#[1] "year"
Or convert to factor
with levels
specified或转换为指定levels
的factor
names(sort(factor(cl, c('integer', 'numeric'))))[1]
#[1] "year"
Or with match
或搭配match
names(cl)[na.omit(match(c('integer', 'numeric'), cl))[1]]
#[1] "year"
Using grep
.使用grep
。
names(sort(cl[grep("integer|numeric", cl)])[1])
# [1] "year"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.