I have the dataframe below and I would like to turn the Sold_Pr
column to numeric by replacing comma
sign with .
subs<-structure(list(Sold_Pr = c("6,500.00", "173,000.00", "60,000.00"
), Area = structure(c(1L, 1L, 1L), .Label = c("411", "415", "981",
"8001", "8002", "8003", "8004", "8005", "8006", "8007", "8008",
"8009", "8010", "8011", "8012", "8013", "8014", "8015", "8016",
"8017", "8018", "8019", "8020", "8021", "8022", "8023", "8024",
"8025", "8026", "8027", "8028", "8029", "8030", "8031", "8034",
"8035", "8037", "8038", "8039", "8040", "8041", "8042", "8043",
"8044", "8045", "8046", "8047", "8048", "8049", "8050", "8051",
"8052", "8053", "8055", "8056", "8057", "8058", "8059", "8060",
"8061", "8062", "8063", "8064", "8065", "8066", "8067", "8068",
"8069", "8070", "8071", "8072", "8073", "8074", "8075", "8076",
"8077"), class = "factor"), Closed_Date = structure(c(18668,
18933, 18716), class = "Date")), row.names = c(NA, -3L), class = c("tbl_df",
"tbl", "data.frame"))
I tried with 3 ways but none of them works.
as.numeric(subs(",", ".", subs$Sold_Pr, fixed = TRUE))
subs$Sold_Pr <- as.numeric(subs$Sold_Pr)
subs$Sold_Pr<-as.numeric(gsub(",", "", subs$Sold_Pr))
CodePudding user response:
One option would be readr::parse_number
:
library(readr)
parse_number(subs$Sold_Pr, locale = locale(decimal_mark = ".", grouping_mark = ","))
#> [1] 6500 173000 60000
CodePudding user response:
Another option:
library(dplyr)
subs %>%
mutate(Sold_Pr = as.numeric(sub(",", "", Sold_Pr)))
Sold_Pr
1 6500
2 173000
3 60000
Data:
subs <- data.frame(
Sold_Pr = c("6,500.00", "173,000.00", "60,000.00")
)
CodePudding user response:
Using gsub
to remove everything but digits, coerce as.numeric
and divide by 100.
as.numeric(gsub('\\D', '', subs$Sold_Pr)) / 100
# [1] 6500 173000 60000