gpt4 book ai didi

string - 删除R中字符串中位置的字符?

转载 作者:行者123 更新时间:2023-12-04 17:53:30 25 4
gpt4 key购买 nike

我正在寻找一种方法来删除 R 中字符串中某些位置的字符。例如,如果我们有一个字符串 "1,2,1,1,2,1,1,1,1,2,1,1" ,我想删除第三,第四,第七和第八位。该操作将使字符串:"1,1,2,1,1,1,1,2,1,1" .

不幸的是,不能使用 strsplit 将字符串分解为列表,因为我使用的字符串长度超过 100 万个字符。考虑到我有大约 2,500 个字符串,这需要相当长的时间。

或者,找到一种用空字符串替换字符的方法 ""会达到同样的目的 - 我认为。考虑到这一思路,我遇到了这篇 StackOverflow 帖子:

R: How can I replace let's say the 5th element within a string?

不幸的是,建议的解决方案很难有效地概括,以下每个输入字符串需要大约 60 秒才能删除 2000 个位置的列表:

subchar2 = function(inputstring, pos){
string = ""
memory = 0
for(num in pos){
string = paste(string, substr(inputstring, (memory+1), (num-1)), sep = "")
memory = num
}
string = paste(string, substr(inputstring,(memory+1), nchar(inputstring)),sep = "")
return(string)
}

查看问题,我发现了一段代码,似乎将某些位置的字符替换为 "-" :
subchar <- function(string, pos) {
for(i in pos) {
string <- gsub(paste("^(.{", i-1, "}).", sep=""), "\\1-", string)
}
return(string)
}

我不太了解正则表达式(还),但我强烈怀疑沿着这些方向的东西会比第一个代码解决方案在时间上更好。不幸的是,当 pos 中的值变高时,这个 subchar 函数似乎中断了:
> test = subchar(data[1], 257)
Error in gsub(paste("^(.{", i - 1, "}).", sep = ""), "\\1-", string) :
invalid regular expression '^(.{256}).', reason 'Invalid contents of {}'

我还考虑尝试使用 SQL 将字符串数据读入表中,但我希望有一个优雅的字符串解决方案。 R 中执行此操作的 SQL 实现似乎相当复杂。

有任何想法吗?
谢谢!

最佳答案

使用 scan() 阅读它们.您可以将分隔符设置为 ","和 what="a"。您可以 scan使用 nlines=1 一次“一行”如果是 textConnection ,“管道”将“记住”上次读取时的位置。

x <- paste( sample(0:1, 1000, rep=T), sep=",")
xin <- textConnection(x)

x995 <- scan(xin, sep=",", what="a", nmax=995)
# Read 995 items
x5 <- scan(xin, sep=",", what="a", nmax=995)
# Read 5 items

这是一个带有 5 条“线”的插图
> x <- paste( rep( paste(sample(0:1, 50, rep=T), collapse=","),  5),  collapse="\n")
> str(x)
chr "1,0,0,0,0,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1,0,0,1,0,1,0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,1,1,0,0,0,1,0,0\n1,0,0,0,0,1,0,0,1,1,1,0,1,"| __truncated__
> xin <- textConnection(x)
> x1 <- scan(xin, sep=",", what="a", nlines=1)
Read 50 items
> x2 <- scan(xin, sep=",", what="a", nlines=1)
Read 50 items
> x3 <- scan(xin, sep=",", what="a", nlines=1)
Read 50 items
> x4 <- scan(xin, sep=",", what="a", nlines=1)
Read 50 items
> x5 <- scan(xin, sep=",", what="a", nlines=1)
Read 50 items
> x6 <- scan(xin, sep=",", what="a", nlines=1)
Read 0 items
> length(x1)
[1] 50
> length(x1[-c(3,4,7,8)])
[1] 46
> paste(x1, collapse=",")
[1] "1,0,0,0,0,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1,0,0,1,0,1,0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,1,1,0,0,0,1,0,0"
>

关于string - 删除R中字符串中位置的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12047096/

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