【问题标题】:substr() takes a vector as a string, not the values of the vector as stringssubstr() 将向量作为字符串,而不是将向量的值作为字符串
【发布时间】:2019-01-16 14:32:38
【问题描述】:

我有一个像这样的字符向量:

Variables <- c("EA10", "EA14", "EA15", "EA16", "EA19", "EA2", "EA21", "EA22", "EA24", "EA25", "EA28")

Variablesdf 的向量。我想从上面向量中的第三个字符中提取(特别是提取数字),我正在使用这个代码:

df3["#Variable"] <- substr(df3["Variables"], start=2,stop=100)

但是,正如您在新的#Variable 向量中看到的那样,它将向量作为字符串,而不是将向量的值作为字符串:为什么?我该如何解决这个问题?

   Variables       #Variable
2       EA10   c("EA10", "EA14", "EA15",
5       EA14   c("EA10", "EA14", "EA15",
6       EA15   c("EA10", "EA14", "EA15",
7       EA16   c("EA10", "EA14", "EA15",

【问题讨论】:

  • 你能展示一个可重复的小例子和预期的输出吗
  • sapply(df3["Variables"], substr, start=2,stop=100) ?
  • 为什么是stop = 100?这与 我想从上面向量中的第三个字符中提取有什么关系

标签: r string substring


【解决方案1】:

当您引用df['Variables'] 时,您提取的是数据帧,而不是向量,并且 substr 不知道如何处理它。使用 df$Variables 或 df[['Variables']],如下所示。

df <- data.frame(Variables = c("EA10", "EA14", "EA15", "EA16", "EA19", "EA2", "EA21", "EA22", "EA24", "EA25", "EA28"))
substr(df[["Variables"]], start = 2, stop = 100)
[1] "A10" "A14" "A15" "A16" "A19" "A2"  "A21" "A22" "A24" "A25" "A28"

【讨论】:

  • 还有:with(df, substring(Variables, 2, 100)).
【解决方案2】:

我想从上面向量中的第三个字符中提取 (具体来说,提取数字)

我会使用gsub(),它会找到一个特定的模式并替换它。

Variables <- c("EA10", "EA14", "EA15")
gsub(pattern="\\D", replacement="", Variables)
#[1] "10" "14" "15"
  • pattern="\\D" 匹配所有非数字(更多here

  • replacement="" 将其替换为空格


作为替代方案,您当然可以直接提取数字,例如使用 str_extract() 包中的 str_extract()

stringr::str_extract(string = Variables, pattern = "\\d+") 
# \\d+ matches multiple digits in the string
#[1] "10" "14" "15"

data.frame 内:

df["Variable"] = gsub(pattern="\\D", replacement="", df["Variable"])

或:

df["Variable"] = stringr::str_extract(df["Variable"], pattern="\\d+")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-27
    • 2017-11-06
    • 2020-11-08
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多