gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:05:12 28 4
gpt4 key购买 nike

给定以下命名向量:

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com