Replace "\\" with "\" in an imported data.frame in R

Viewed 39

I have next csv file:

x,y,label
2,3,A
3,4,C\n2
4,5,B

"\n" in the csv file means a second line. But, when I import this file, R replace "\n" with "\\n". And when use ggplot, generates a graph without a second line:

library(ggplot2)
data <- read.csv("text.txt")
ggplot(data = data, aes(x=x, y=y)) +
  geom_text(aes(label = label))

enter image description here

I tried to use data$label <- gsub("\\\\", "\\", data$label) but replace "C\n2" to "Cn2".

I tried to use cat inside to geom_text: label = cat(label). But return error.

I can modified manually with data$label[2] <- "C\n2":

data$label[2] <- "C\n2"
ggplot(data = data, aes(x=x, y=y)) +
  geom_text(aes(label = label))

enter image description here

but it requires automating for a larger amount of data.

How can I keep "\n"?

1 Answers

We could replace the \ with sub

data$label <- sub("\\\\n", "\n", data$label)

Now, using the OP's code for ggplot

library(ggplot2)
ggplot(data = data, aes(x=x, y=y)) +
   geom_text(aes(label = label))

enter image description here

data

data <- structure(list(x = 2:4, y = 3:5, label = c("A", "C\\n2", 
 "B")), class = "data.frame", row.names = c(NA, -3L))
Related