简体   繁体   English

在指定位置之后替换字符串中的所有元素

[英]Replace all elements in string after a specified position

I would like to replace all elements in a string after a specified position that varies among strings. 我想在字符串之间的指定位置之后替换字符串中的所有元素。 Ideally the solution would use regex in base R . 理想情况下,解决方案将在基数R使用regex

Here is a worked example and the desired result: 这是一个可行的示例和所需的结果:

my.last.position <- c(5, 7, 3, NA, 10)

my.data <- read.table(text='
                         my.string
                         .1.222.2.2
                         ..1..1..2.
                         1.1.2.2...
                         .222.232..
                         ..1..1...1
', header=TRUE, stringsAsFactors = FALSE)
my.data

desired.result <- read.table(text='
                         my.string
                         .1.22.....
                         ..1..1....
                         1.1.......
                         .222.232..
                         ..1..1...1
', header=TRUE, stringsAsFactors = FALSE)
desired.result

The vector my.last.position specifies the last position to retain in each string. 向量my.last.position指定要保留在每个字符串中的最后位置。 The data.frame desired.result contains the desired result. 所述data.frame desired.result包含所期望的结果。

Thanks for any advice. 感谢您的任何建议。 Sorry if this is a duplicate. 抱歉,如果这是重复的。

Hopefully someone can come up with a more elegant solution than this, but here goes: 希望有人可以提出比这更优雅的解决方案,但是这里有:

mapply(
    function(s,i) paste(collapse='',if (is.na(i)) s else c(s[seq_len(i)],rep('.',length(s)-i))),
    strsplit(my.data$my.string,''),
    my.last.position
);
## [1] ".1.22....." "..1..1...." "1.1......." ".222.232.." "..1..1...1"

Here is another method. 这是另一种方法。 Not sure that it is any more elegant: 不知道它是否更优雅:

# as in the example output, any NAs are treated as do not mess with this
# vector element
my.last.position.NoNA <- ifelse(is.na(my.last.position),
                                nchar(my.data$my.string), my.last.position)

# perform the replacement
paste0(substr(my.data$my.string, 1, my.last.position.NoNA), 
  sapply(1:nrow(my.data), function(i) paste0(rep(".", 
                length=(nchar(my.data$my.string[i])-my.last.position[i])),
                collapse="")))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM