Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
839 views
in Technique[技术] by (71.8m points)

regex - how to replace nth character of a string in a column in r

My input is

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

I want my output to be

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

please help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If things are as consistent as you show and you want to replace the 7th character then substring may be a good way to go, but you made the column character by wrapping with data.frame without stringsAsFactors = FALSE. You'd need to make the column character first:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...