Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 615
areddy Avatar asked Aug 01 '15 12:08

areddy


People also ask

How do I replace a character in a column in R?

Use str_replace() to Replace Character in a String packages("stringr") . It is used to replace a part of a string (character) on a column with another string or a character.

How do you replace a string in R studio?

Use str_replace() method from stringr package to replace part of a column string with another string in R DataFrame.


1 Answers

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
like image 182
Tyler Rinker Avatar answered Sep 30 '22 10:09

Tyler Rinker