简体   繁体   English

在 R 中有条件地提取向量名称

[英]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:您已经很接近了,但是到目前为止,您的方法存在两个问题:

  1. The || || operator only works with one element;运算符仅适用于一个元素; since you're looking over more than one you would want |因为您要查看的不止一个| instead.反而。 See ?`||` for more details.请参阅?`||`了解更多详情。
  2. Your approach would treat "integer" and "numeric" equally, rather than prioritising numeric as you would prefer.您的方法将平等对待“整数”和“数字”,而不是按照您的喜好优先考虑数字。

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或转换为指定levelsfactor

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.

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