将货币字符转换为R中的数字

问题描述 投票:0回答:1

我有这个数据集,该数据集的字符格式为货币,带有磅符号,后面加百万的“ m”。我正在尝试对数字进行一些计算,因此需要数字格式而不是字符格式。

这是原始数据帧的第一行

   Item     Money_In    total_bought  Money_Out  total_sold  Net_Spend
1  unit1    £192.60m    15            £64.78m    13          £-127.82m

我正在尝试使输出表如下:

   Item     Money_In    total_bought  Money_Out  total_sold  Net_Spend
1  unit1    192600000   15            64780000   13          -127820000

谢谢

r dataframe currency
1个回答
0
投票

这里是dplyr解决方案:

df %>% 
  mutate_at(vars(Money_In, Money_Out, Net_Spend),
            list( ~ str_sub(., 2, -2))) %>% 
  mutate_at(vars(Money_In, Money_Out, Net_Spend),
            list(as.numeric)) %>% 
  mutate_at(vars(Money_In, Money_Out, Net_Spend),
            list(~. * 1000000))

dput:

df <- structure(list(Item = "unit1", Money_In = "£192.60m", total_bought = 15, 
    Money_Out = "£64.78m", total_sold = 13, Net_Spend = "£-127.82m"), row.names = c(NA, 
-1L), class = c("tbl_df", "tbl", "data.frame"))
© www.soinside.com 2019 - 2024. All rights reserved.