首页 > 解决方案 > 用r中的奇怪字符解析数字

问题描述

我有以下数据框。我想将这些数字更改为 dbl 形式。

> df1
# A tibble: 44 x 4
   unit_price total_amount unit_price_2 total_amount_2
   <chr>      <chr>        <chr>        <chr>         
 1 3,500.00   3,500.00     10,000.00    10,000.00     
 2 4.50       2,565.00     14.00        7,980.00      
 3 9.00       234.00       18.00        468.00        
 4 7.50       15,000.00    9.50         19,000.00     
 5 15.00      3,960.00     14.00        3,696.00      
 6 15.00      6,750.00     14.00        6,300.00      
 7 25.00      6,525.00     22.00        5,742.00      
 8 48.00      251,875.20   41.00        215,143.40    
 9 48.00      357,163.20   41.00        305,076.90    
10 55.00      11,000.00    41.00        8,200.00      
# … with 34 more rows

但是,一排具有以下“-”字符。所以我无法得到预期的结果。我该如何处理这个问题?

> df1[12,]
# A tibble: 1 x 4
  unit_price total_amount      unit_price_2 total_amount_2   
  <chr>      <chr>             <chr>        <chr>            
1 1.00       -          997.00 1.00         -          997.00
> df1 %>% mutate_at(1:4, parse_number)
Warning: Problem with `mutate()` input `total_amount`.
ℹ 1 parsing failure.
row col expected            actual
 12  -- a number -          997.00

标签: rtidyverse

解决方案


parse_number函数有一个na=参数,因此您可以告诉它哪些值被视为缺失(这可能是您想要使用“-”执行的操作)。

利用

df1 %>% mutate_at(1:4, parse_number, na="-")

检查?parse_number帮助页面以获取其他选项。


推荐阅读