【问题标题】:How can I eliminate the first x number of elements from each part of a character vector in R? [duplicate]如何从 R 中的字符向量的每个部分中消除前 x 个元素? [复制]
【发布时间】:2021-07-19 03:37:45
【问题描述】:

我有以下长度为 3 的字符向量:

test <- c("old_information", "old_car", "old_sting")

typeof(test) --> [1] "character"
length(test) --> [1] 3

我想遍历test 的每个元素,所以它最终变成相当于:

test <- c("information", "car", "sting")

换句话说:我想保持字符数组的长度,但从每个组件中删除相同数量的元素(每个元素前面拼写“old_”的 4 个字符。)

我该怎么做?

【问题讨论】:

  • test &lt;- sub('old_', '', test)
  • 漂亮!简单而优雅。谢谢!

标签: r


【解决方案1】:

我认为您实际上可能需要一些正则表达式替换逻辑:

test <- c("old_information", "old_car", "old_sting")
output <- sub("^.*?_", "", test)
output

[1] "information" "car"         "sting"

这将删除从每个字符串的开头到第一个下划线(包括第一个下划线)的所有内容。如果您的逻辑真的是去掉前 5 个字符,那么只需使用 substr

output <- substr(test, 5, nchar(test))

【讨论】:

    猜你喜欢
    • 2014-06-18
    • 2020-04-06
    • 1970-01-01
    • 2018-10-30
    • 2021-04-26
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多