How to replace the nth character of a row in a column in r

My input

a<-c("aa_bbb_cc_ddd","ee_fff_gg_hhh")
b<-c("a","b")
df<-data.frame(cbind(a,b))

      

I want my conclusion to be

a<-c("aa_bbb-cc_ddd","ee_fff-gg_hhh")
b<-c("a","b")
df<-data.frame(cbind(a,b))

      

please, help

+3


source to share


3 answers


You can use sub,

sub("^([^_]*_[^_]*)_", "\\1-",df$a)

      



Example:

> a<-c("aa_bbb_cc_ddd","ee_fff_gg_hhh")
> b<-c("a","b")
> df<-data.frame(cbind(a,b))
> df
              a b
1 aa_bbb_cc_ddd a
2 ee_fff_gg_hhh b
> df$a <- sub("^([^_]*_[^_]*)_", "\\1-",df$a)
> df
              a b
1 aa_bbb-cc_ddd a
2 ee_fff-gg_hhh b

      

+4


source


If things are as consistent as you show and you want to replace the 7th character, then it substring

might be a good way to go, but you made a column character by wrapping data.frame

without stringsAsFactors = FALSE

. First you need to create a column symbol:



df$a <- as.character(df$a)
substring(df$a, 7, 7) <- "-"
df

##               a b
## 1 aa_bbb-cc_ddd a
## 2 ee_fff-gg_hhh b

      

+4


source


Here's a general way to replace the nth occurrence _

with -

.

n <- 2

# create regex pattern based on n
pat <- paste0("^((?:.*?_){", n - 1, "}.*?)_")
# [1] "^((?:.*?_){1}.*?)_"

# replace character
sub("^((?:.*?_){1}.*?)_", "\\1-", df$a, perl = TRUE)
# [1] "aa_bbb-cc_ddd" "ee_fff-gg_hhh"

      

+3


source







All Articles