1

In a dataframe like this:

a <- c(rep ("C-B", 4), rep("C_C", 6))
b <- c(rep ("B-B", 4), rep("B_C", 6))
c <- c(rep ("A-B", 4), rep("A_C", 6))
data1 <- data.frame (a, b, c)

I would like to replace in the whole dataframe the "_" with "-"

I tried this but it does not work properly:

data2 <- gsub('_', '-', data1)

What should I change?

jay.sf
  • 60,139
  • 8
  • 53
  • 110
Kkyr
  • 55
  • 7

1 Answers1

2

What about using lapply as follows

> data1 <- data.frame(lapply(data1, function(x) {gsub("_", "-", x)}))

or even better

> data1[] <- lapply(data1, function(x) {gsub("_", "-", x)})
> data1
     a   b   c
1  C-B B-B A-B
2  C-B B-B A-B
3  C-B B-B A-B
4  C-B B-B A-B
5  C-C B-C A-C
6  C-C B-C A-C
7  C-C B-C A-C
8  C-C B-C A-C
9  C-C B-C A-C
10 C-C B-C A-C
keepAlive
  • 6,369
  • 5
  • 24
  • 39
  • 3
    No need to call `data.frame`. You can update existing data frame. See Ronak's comment – Sotos Jan 08 '19 at 10:00