gpt4 book ai didi

r - 如何替换字符串中某个位置的某个字符?

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

我有一个问题是如何替换某个位置的字符。例如:

str <- c("abcdccc","hijklccc","abcuioccc")
#I want to replace character "c" which is in position 3 to "X" how can I do that?
#I know the function gsub and substr, but the only idea I have got so far is
#use if() to make it. How can I do it quickly?
#ideal result
>str
"abXdccc" "hijklccc" "abXuioccc"

最佳答案

这有点尴尬,但是您可以根据单个字符的值替换单个字符,例如:

ifelse(substr(str,3,3)=="c", `substr<-`(str,3,3,"X"), str)
#[1] "abXdccc" "hijklccc" "abXuioccc"

如果您愿意覆盖该值,则可以将其做得更简洁:
substr(str[substr(str,3,3)=="c"],3,3) <- "X"
str
#[1] "abXdccc" "hijklccc" "abXuioccc"

关于r - 如何替换字符串中某个位置的某个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50963557/

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