R ProgrammingServer Side ProgrammingProgramming

• First of all, create a data frame.

• Then, use gsub function along with lapply function to remove dollar sign.

## Example

#### Create the data frame

Let’s create a data frame as shown below −

Product<-sample(c("Milk","Sugar","Bread","Wheat"),25,replace=TRUE)
Price<-
sample(c("$10","$5","$12","$15","$9","$8","$11","$14","$13"),25,replace=TRUE) df<-data.frame(Product,Price) df ## Output On executing, the above script generates the below output(this output will vary on your system due to randomization) −  Product Price 1 Milk$11
2  Sugar   $5 3 Milk$5
4  Bread   $10 5 Sugar$8
6  Sugar   $11 7 Sugar$5
8  Wheat   $15 9 Sugar$5
10 Wheat   $15 11 Wheat$5
12 Milk    $8 13 Milk$13
14 Wheat   $13 15 Wheat$5
16 Milk    $13 17 Wheat$12
18 Bread   $5 19 Bread$10
20 Milk    $9 21 Milk$14
22 Bread   $11 23 Milk$8
24 Sugar   $10 25 Bread$8

Remove dollar sign

Using gsub function along with lapply function to remove dollar sign from Price column as shown below −

Product<-sample(c("Milk","Sugar","Bread","Wheat"),25,replace=TRUE)
Price<-
sample(c("$10","$5","$12","$15","$9","$8","$11","$14","$13"),25,replace=TRUE) df<-data.frame(Product,Price) df[]<-lapply(df,gsub,pattern="$",fixed=TRUE,replacement="")
df

## Output

   Product Price
1  Sugar    15
2  Sugar    14
3  Wheat     8
4  Sugar    10
5  Milk     11
6  Milk      5
7  Sugar    11
8  Sugar    14
9  Milk     12
10 Wheat    10
11 Wheat    15
14 Milk      5
25 Milk      5