gpt4 book ai didi

r - 从 R 中给定条件后的列 'n' 个字符中删除字符

转载 作者:行者123 更新时间:2023-12-04 17:06:49 24 4
gpt4 key购买 nike

我想删除此列中 '18' 后 3 个字符的所有内容

MGL18JUNFUT
NATIONALUM18JUNFUT
NTPC18JUNFUT
ONGC18JUNFUT
PCJEWELLER18JUNFUT
PEL18JUNFUT
PFC18JUNFUT
PIDILITIND18JUNFUT
POWERGRID18JULFUT
PTC18JULFUT
RAYMOND18JULFUT
RBLBANK18JULFUT
RECLTD18JULFUT
RPOWER18JULFUT
MGL18JUN800PE

我希望我的输出看起来像
MGL18JUN
NATIONALUM18JUN
NTPC18JUN
ONGC18JUN
PCJEWELLER18JUN
PEL18JUN
PFC18JUN
PIDILITIND18JUN
POWERGRID18JUL
PTC18JUL
RAYMOND18JUL
RBLBANK18JUL
RECLTD18JUL
RPOWER18JUL
MGL18JUN

我试过下面的代码。
output <- sub('(^.*?)18???.*', '' , df$column)

但是输出来了
8JUNFUT
8JUNFUT
8JUNFUT
8JUNFUT
8JUNFUT
8JUNFUT
8JUNFUT
8JUNFUT
8JUNFUT
8JUNFUT
8JUNFUT
8JUNFUT
8JUNFUT
8JUNFUT
8JUN800PE

与此等效的 Excel 是。
=LEFT(A1, FIND("18",A1,1) +4)

我尝试了许多其他选项,如 sub、gregexpr、substr,但似乎没有任何效果

最佳答案

我们可以更改 sub通过在组 ( .* ) 中捕获字符模式 ( .{0,3} 后跟 18 然后零到三个字符 ( .{3} 或特别是 3 个字符 ( (...) ) 并替换为反向引用 ( \\1 )被捕获组的

sub("^(.*18.{0,3}).*", "\\1", df$column)

或者
sub("^(.*18.{3}).*", "\\1", df$column)
#[1] "MGL18JUN" "NATIONALUM18JUN" "NTPC18JUN" "ONGC18JUN"
#[5] "PCJEWELLER18JUN" "PEL18JUN" "PFC18JUN" "PIDILITIND18JUN"
#[9] "POWERGRID18JUL" "PTC18JUL" "RAYMOND18JUL" "RBLBANK18JUL"
#[13] "RECLTD18JUL" "RPOWER18JUL" "MGL18JUN"

根据 OP 的评论,如果有 18 个的多个实例
v1 <- "PIDILITIND18JUN1180CE"
sub("^(.*?18.{3}).*", "\\1", v1)

它也适用于初始数据
sub("^(.*?18.{3}).*", "\\1", df$column)
#[1] "MGL18JUN" "NATIONALUM18JUN" "NTPC18JUN" "ONGC18JUN"
#[5] "PCJEWELLER18JUN" "PEL18JUN" "PFC18JUN" "PIDILITIND18JUN"
#[9] "POWERGRID18JUL" "PTC18JUL" "RAYMOND18JUL" "RBLBANK18JUL"
#[13] "RECLTD18JUL" "RPOWER18JUL" "MGL18JUN"

数据
df <- structure(list(column = c("MGL18JUNFUT", "NATIONALUM18JUNFUT", 
"NTPC18JUNFUT", "ONGC18JUNFUT", "PCJEWELLER18JUNFUT", "PEL18JUNFUT",
"PFC18JUNFUT", "PIDILITIND18JUNFUT", "POWERGRID18JULFUT", "PTC18JULFUT",
"RAYMOND18JULFUT", "RBLBANK18JULFUT", "RECLTD18JULFUT", "RPOWER18JULFUT",
"MGL18JUN800PE")), .Names = "column", class = "data.frame",
row.names = c(NA,
-15L))

关于r - 从 R 中给定条件后的列 'n' 个字符中删除字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51075073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com