Diggy Detroit Diggy Detroit - 11 days ago 5
R Question

Find and replace cells with asterisk, *

I have a dataframe where some of the cells contain * values.

RowNumber Col1
1 *
2 **
3 A123
4 ****
5 123


I am trying to replace these * values with blank/empty values

Desired Output

RowNumber Col1
1
2
3 A123
4
5 123


Any advise on accomplishing this is much appropriated.

Answer

We can use regex to replace the * with blanks (""). The * is a metacharacter representing zero or more characters. So, we need to escape it (\\*), or place it inside square brackets ([*]) to read it as the literal * character`

df1$Col1 <- gsub("[*]+", "", df1$Col1)
df1$Col1
#[1] ""     ""     "A123" ""     "123"

Or use the fixed=TRUE argument

gsub("*", "", df1$Col1, fixed = TRUE)
Comments