【问题标题】:Find the line of the match character找到匹配字符的行
【发布时间】:2021-04-21 06:39:14
【问题描述】:
我想查看字符所在的行。
预期的答案是包含字符 BTC 的 4 行数字。
library(stringr)
library(quantmod)
symbols <- stockSymbols()
symbols <- symbols[,1]
u <- symbols
a <- "BTC"
str_detect(a, u)
table(str_detect(a, u))
【问题讨论】:
标签:
r
dplyr
tidyverse
tidyr
data-manipulation
【解决方案1】:
您可以使用grep 获取模式a 出现的索引。
#Index
grep(a, u)
#[1] 3437
#Value
grep(a, u, value = TRUE)
#[1] "EBTC"
使用stringr:
library(stringr)
#Index
str_which(u, a)
#Value
str_subset(u, a)
【解决方案2】:
您可以使用 tidyverse 方式,使用 filter() 函数:
filter(dataset, column == "BTC")
或者使用基础 R 中的 grep() 函数:
grep("BTC", dataset$column)
这将为您提供您正在寻找的内容的索引(即位置)
【解决方案3】:
我们可以使用grepl 和which
which(grepl(a, u))
【解决方案4】:
另一个基本 R 选项可能是 which + regexpr(但我认为 grep 或 grepl 显然更有效和直接)
which(regexpr(a, u)>0)