1

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.

AleG
  • 153
  • 8
  • 3
    Tried `gsub(".", "\r", df$col1, fixed=TRUE)` yet? – Wiktor Stribiżew Oct 08 '20 at 11:58
  • @WiktorStribiżew That gives this back: `name\rsurname`. Also, reading documentation I think it has to be fixed= FALSE? So it does the replacement using regular expression and not as a literal string. – AleG Oct 08 '20 at 12:01
  • 2
    Aleg, it does not **NOT** give back `\r` as part of *literal text*. The `\r` is a part of the *string literal*. See my answer. `fixed=FALSE` is only required when you need to use a regex. Not the case here. – Wiktor Stribiżew Oct 08 '20 at 12:06
  • Oh I understand, did not know it worked like that, thanks. I´m curious, is possible for literal text to have returns, new lines, etc. as an element of a vector in R? – AleG Oct 08 '20 at 12:12
  • Ok so although it is displayed as text\rtext the return is actually there, thanks!! – AleG Oct 08 '20 at 12:20

1 Answers1

3

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563