xyz
xyz

Reputation: 79

converting cents in dollars of a column

I have a column in my df as given and I want to convert values which are in cents into dollars and those which are in dollars I want them as it is.

DF Data set has two columns Destination and money I want to convert those values which are in cents to the dollar in money column and those which are in dollars I want them as it is

Upvotes: 0

Views: 624

Answers (1)

Zhiqiang Wang
Zhiqiang Wang

Reputation: 6769

There are more elegant ways to do this. This is my approach for now:

df <- data.frame(
    money = c("69¢", "40.6¢", "91.3¢", "50¢", "4¢", "$1.17", "$1", "$1.30")) 
dollar = as.character(df$money)
cents <- as.numeric(unlist(strsplit(dollar, "¢"))) 
dollar[!is.na(cents)]<-paste0("$", round((cents/100), 2))
df$money = dollar
df

> df
  money
1 $0.69
2 $0.41
3 $0.91
4  $0.5
5 $0.04
6 $1.17
7    $1
8 $1.30

Upvotes: 2

Related Questions