我有一个数据框,想要清理那些包含字符价格的列。我想去掉美元符号和逗号分隔符,并将这些列转换为数字类型。
structure(list(Sold.Price = c("", "$177,500", "$180,000", "$180,000",
"$189,000"), Title.to.Land = c("Freehold Strata", "Freehold Strata",
"Freehold Strata", "Freehold Strata", "Freehold Strata"), Price = c("$174,900",
"$177,500", "$180,000", "$180,000", "$189,000"), DOM = c(93L,
34L, 39L, 56L, 2L), List.Date = c("10/4/2019", "12/12/2019",
"12/9/2019", "11/12/2019", "1/9/2020"), MaintFee = c("$2,916.00",
"$373.80", "$331.57", "$320.42", "$1,055.67")), row.names = c(NA,
5L), class = "data.frame")
Sold.Price Title.to.Land Price DOM List.Date MaintFee
1 Freehold Strata $174,900 93 10/4/2019 $2,916.00
2 $177,500 Freehold Strata $177,500 34 12/12/2019 $373.80
3 $180,000 Freehold Strata $180,000 39 12/9/2019 $331.57
4 $180,000 Freehold Strata $180,000 56 11/12/2019 $320.42
5 $189,000 Freehold Strata $189,000 2 1/9/2020 $1,055.67
我尝试了这种方法:
combined_csv$Sold.Price <- gsub("\\$", "", combined_csv$Sold.Price)
combined_csv$Sold.Price <- gsub("\\,", "", combined_csv$Sold.Price)
combined_csv$Sold.Price <- as.numeric(combined_csv$Sold.Price)
但这看起来并不聪明。我希望能在一行中完成所有价格类型列(Sold.price,Maintfee等)的操作。我该如何做到?
\\D*
- AnilGoyalcombined_csv$Sold.Price <- gsub("\\D", "", combined_csv$Sold.Price)
吗?但即使我这样做了,我有多个列,我应该逐一为每个列进行操作。我想找到一种方法,首先列出我想要更改的列的名称,然后一次性进行更改。 - Ross_you\\D*
不起作用,因为它会将33.4这样的数字中的.
删除,并将其更改为334,这是错误的。 - Ross_you