R:如何对命名向量中的元素窗口进行切片

标签 r vector

给定以下命名向量:

x <- c(54, 36, 67, 25, 76)
names(x) <- c('a', 'b', 'c', 'd', 'e')

如何提取“b”和“d”之间的元素?我可以使用 dplyr::select(dt, b:d) 对数据表执行此操作,但出于某种原因,我找不到命名向量的解决方案(我找到的所有示例都是用于提取元素的(s) 通过给出所有名称而不是名称范围)...

最佳答案

你可以做

x[which(names(x) == "b"):which(names(x) == "d")]
#>  b  c  d 
#> 36 67 25 

问题是在命名向量中不能保证名称是唯一的,如果有重复的名称,整个概念就变得毫无意义。

如果你想要一个完整的解决方案,允许 tidyverse 风格的非标准评估和合理的错误消息,你可以拥有

subset_named <- function(data, exp)
{
  if(missing(exp)) return(data)
  exp <- as.list(match.call())$exp
  if(is.numeric(exp)) return(data[exp])
  if(is.character(exp)) return(data[exp])
  
  tryCatch({
    ss <- suppressWarnings(eval(exp))
    return(data[ss])},
    error = function(e)
    {
      if(as.character(exp[[1]]) != ":")
        stop("`exp` must be a sequence created by ':'")
      n <- names(data)
      first <- as.character(exp[[2]])
      second <- as.character(exp[[3]])
      first_match <- which(n == first)
      second_match <- which(n == second)
      if(length(first_match) == 0)
        stop("\"", first, "\" not found in names(", 
             deparse(substitute(data)), ")")
      if(length(second_match) == 0)
        stop("\"", second, "\" not found in names(", 
             deparse(substitute(data)), ")")
      if(length(first_match) > 1) {
        warning("\"", first, 
                "\" found more than once. Using first occurence only")
        first_match <- first_match[1]
      }
      if(length(second_match) > 1) {
        warning("\"", second, 
                "\" found more than once. Using first occurence only")
        second_match <- second_match[1]
      }
      return(data[first_match:second_match])
    })
}

这允许以下行为:

subset_named(x, "b":"d")
#>  b  c  d 
#> 36 67 25

subset_named(x, b:d)
#>  b  c  d 
#> 36 67 25

subset_named(x, 1:3)
#>  a  b  c 
#> 54 36 67

subset_named(x, "e")
#>  e 
#> 76

subset_named(x)
#>  a  b  c  d  e 
#> 54 36 67 25 76

关于R:如何对命名向量中的元素窗口进行切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63762710/

相关文章:

C++/GLM : Calculate screen position of vertex

c++ - 如何在指针中保存 vector 元素的详细信息?

r - 如何在终端的脚本中显示 r 中的绘图

R:在填充数据框 B 中的一行之前,使用某个日期的数据框 A 中的值

c++ - 如何正确使用指针 vector ?

c++ - 传递命令行参数

r - 如何在 R 包中存储经常使用的数据或参数?

r - 创建一个新列作为列表返回

r - 绕过 data.table::fread 中的 "ghost"换行符或文件结尾 (EOF)

c++ - 为什么要在实例替换 vector 中删除?