假设我有一列:
是否有使用 tidyverse 根据模式列表将列拆分为两列的简单方法?
例如,列表将包含 c(ATOM, SOL, BUSD, UNI) 并且基于此列表,列将像这样拆分
谢谢
PS:我只能以一种非常复杂的方式来搜索和删除模式,所以我正在寻找一个更简单的解决方案。
答案 0 :(得分:2)
这是一个想法。我们可以构造正确的正则表达式调用,然后使用extract
来分割数据。在此示例中,我假设您需要找到包含 target_string
中的字符串的第一列,同时将所有内容保留在第二个字符串中。
library(tidyverse)
target_string <- c("ATOM", "SOL", "UNI")
target_regex <- paste0("(", paste0(paste0("^", target_string), collapse = "|"), ")(.*)")
dat2 <- dat %>%
extract(Text, into = c("Col1", "Col2"), regex = target_regex)
dat2
# # A tibble: 5 x 2
# Col1 Col2
# <chr> <chr>
# 1 ATOM BUSD
# 2 SOL BTC
# 3 SOL BUSD
# 4 SOL BUSD
# 5 UNI BUSD
数据
dat <- tribble(
~Text,
"ATOMBUSD",
"SOLBTC",
"SOLBUSD",
"SOLBUSD",
"UNIBUSD"
)
答案 1 :(得分:2)
创建一串模式并使用 str_extract_all
提取相关关键字。
使用@www 的数据:
library(stringr)
target_string <- c("ATOM", "SOL", "UNI", "BUSD", "BTC")
do.call(rbind, str_extract_all(dat$Text, str_c(target_string, collapse = '|')))
# [,1] [,2]
#[1,] "ATOM" "BUSD"
#[2,] "SOL" "BTC"
#[3,] "SOL" "BUSD"
#[4,] "SOL" "BUSD"
#[5,] "UNI" "BUSD"
或类似的基本 R 方式:
do.call(rbind, regmatches(dat$Text, gregexpr(paste0(target_string, collapse = '|'), dat$Text)))
答案 2 :(得分:0)
这样的事情怎么样:
echo '\n\rnewtableData' >> filename
带有零宽度正则表达式的 rx <- "^(ATOM|SOL|BUSH|UNI)(.*)$"
d %>% cbind( str_match( .$Pair, rx )[,-1] )
可能有效,但不支持可变宽度的零宽度模式。一段时间。这真是一种耻辱。