【问题标题】:Subsetting over a vector with another vector用另一个向量对一个向量进行子集化
【发布时间】:2018-03-30 23:35:51
【问题描述】:

假设我有一个类似的向量

vector = c('hello','world')

还有另外两个向量,比如

vector2 = c(2,4)
vector3 = c(4,5)

如何创建第四个向量,它是第一个向量中每个元素与其他两个向量的子集?类似的东西

vector[1][vector2[1]:vector3[1]]

所以对于这些向量它会是

vector4 = ('ell','ld')

我曾尝试使用 sapply,但遇到了障碍,因为我不确定如何编写函数来对它们进行子集化。

vector4 = sapply(vector, function(x) x[vector2:vector3])

【问题讨论】:

    标签: r vector subset apply


    【解决方案1】:

    这由substr/substring 覆盖,它将遍历每个输入:

    substr(vector, vector2, vector3)
    substring(vector, vector2, vector3)
    #[1] "ell" "ld" 
    

    这两个功能略有不同。 substring 将扩展到更长的输入并回收:

    substring(c("hello","nopes"), 1:3, 2:4)
    #[1] "he" "op" "ll"
    substr(c("hello","nopes"), 1:3, 2:4)
    #[1] "he" "op"
    

    当您想从单个字符串中提取多个子字符串时,这可能特别有用:

    substring("hello", 1:3, 2:4)
    #[1] "he" "el" "ll"
    substr("hello", 1:3, 2:4)
    #[1] "he"
    

    【讨论】:

    • @d.b - substrsubstring 是 2 个不同的函数。
    • 优于mapply
    • 谢谢,比我想象的要简单得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多