Reputation: 173
I´ve tried a lot of regex patterns and I´ve looked in other answers but have not managed to replace a dot with a carriage return in R. Here is a reprex:
col1 = c( "name.surname", "name.surname", "name.surname")
df <- as.data.frame( col1 )
# returns:
col1
1 name.surname
2 name.surname
3 name.surname
I´ve tried many patterns like this:
gsub( "[.]", "[\\r]", df$col1 )
# returns:
[1] "name[r]surname" "name[r]surname" "name[r]surname"
# desired output:
[1] "name "name "name
surname" surname" surname"
I´d really appreciate if you could help me or point me to a similar question.
Best regards.
Upvotes: 1
Views: 876
Reputation: 626926
You should use
gsub(".", "\r", df$col1, fixed=TRUE)
The "\r"
is a string literal defining a carriage return, "\\r"
is a combination of \
and r
.
Since you need to replace a literal character with another literal character you do not need a regex, hence the fixed=TRUE
argument.
See the R demo online:
col1 = c( "name.surname", "name.surname", "name.surname")
df <- as.data.frame( col1 )
gsub(".", "\r", df$col1, fixed=TRUE)
cat(gsub(".", "\r", df$col1, fixed=TRUE), collapse="\n")
Output:
[1] "name\rsurname" "name\rsurname" "name\rsurname"
name
surname name
surname name
surname
I inlcuded cat(...)
on purpose, just to show the literal text output after gsub
operation, since many believe the real text contains some escape sequences and not literal chars. Also, see Remove backslashes from character string to avoid this misunderstanding.
Upvotes: 3