# How to replace $sign combined with some specific values in an R data frame? Sometimes we get very dirty data and that is the reason data analysis is a difficult task. Most of the data scientists look for clean data but it is almost impossible due to data warehouses often just focus on the data availability instead of the quality of data. One of the head scratching situations is getting an unnecessary value placed at different position in a random manner,$ sign is also a that type of value. We can remove this from an R data frame by using lapply function.

## Example

Consider the below data frame:

Live Demo

> x<-sample(c("A","$B","C"),20,replace=TRUE) > y<-sample(c("I","II","$II"),20,replace=TRUE)
> df1<-data.frame(x,y)
> df1

## Output

x y
1 C $II 2 C II 3 A I 4$B $II 5$B $II 6 A I 7 A$II
8 C I
9 $B II 10$B II
11 C $II 12 A II 13$B II
14 C I
15 C $II 16 C I 17 C II 18$B I
19 $B II 20 C$II

> df1

## Output

 "II" "II" "I" "II" "II" "I" "II" "I" "II" "II" "II" "II" "II" "I" "II"
 "I" "II" "I" "II" "II"

Let’s have a look at another example:

## Example

Live Demo

> Price<-sample(c("1$","2$","3$","4$"),20,replace=TRUE)
> Group<-sample(c("$First","$Second","Third"),20,replace=TRUE)
> df2<-data.frame(Price,Group)
> df2

## Output

Price Group
1 3Second
2 2$Third 3 1$ Third
4 2Second
5 2First
6 4First
7 2First
8 3First
9 2$Third 10 4$ Third
11 3First
12 3$Third 13 3$ $Second 14 2$ $First 15 4$ Third
16 3First
17 4$Third 18 2$ $First 19 2$ $Second 20 3$ Third

> df2

## Output

$Price  "3" "2" "1" "2" "2" "4" "2" "3" "2" "4" "3" "3" "3" "2" "4" "3" "4" "2" "2"  "3"$Group
 "Second" "Third" "Third" "Second" "First" "First" "First" "First"
 "Third" "Third" "First" "Third" "Second" "First" "Third" "First"
 "Third" "First" "Second" "Third"

Updated on: 19-Nov-2020

53 Views 