首页 > 解决方案 > 从数据列中删除点

问题描述

我是处理 R 和使用字符串的初学者。我一直在尝试从数据中删除句点,但不幸的是我找不到解决方案。

这是我在数据框中处理的数据df

df <- read.table(text = " n   mesAno          receita
                 97   1/2009 3.812.819.062,06
                 98   2/2009 4.039.362.599,36
                 99   3/2009 3.652.885.587,18
                 100  4/2009 3.460.247.960,02
                 101  5/2009 3.465.677.403,12
                 102  6/2009 3.131.903.622,55
                 103  7/2009 3.204.983.361,46
                 104  8/2009 3.811.786.009,24
                 105  9/2009 3.180.864.095,05
                 106 10/2009 3.352.535.553,88
                 107 11/2009 5.214.148.756,95
                 108 12/2009 4.491.795.201,50
                 109  1/2010 4.333.557.619,30
                 110  2/2010 4.808.488.277,86
                 111  3/2010 4.039.347.179,81
                 112  4/2010 3.867.676.530,69
                 113  5/2010 6.356.164.873,94
                 114  6/2010 3.961.793.391,19
                 115  7/2010    3797656130.81
                 116  8/2010    4709949715.37
                 117  9/2010    4047436592.12
                 118 10/2010    3923484635.28
                 119 11/2010    4821729985.03
                 120 12/2010    5024757038.22", 
header = TRUE, 
stringsAsFactors = TRUE)

我的目标是将receita列转换为数字,因为它被存储为因子。但是应用转换函数 likeas.numeric(as.factor(x))在 97:114 间隔内不起作用(它强制转换为 NA)。

我想这是因为本专栏中分隔十亿/百万/千的时期。3812819062.06仅当我有类似115:120的内容时,上述转换函数才会起作用。

我尝试改变数据集添加另一列和建模。我真的不知道我在做什么是否很好,但我也尝试将异常数字提取到变量中,并在它们上应用 sub/gsub 但没有成功。

是否有一些直接的方法可以做到这一点,即指示它删除第一次出现的 2 个“。” 然后用“。”替换逗号?我非常有信心我需要的功能是,gsub但我很难找到正确的用法。任何帮助将不胜感激。

编辑:我的方法使用dplyr::mutate(). 丑陋但有效。

df <- df %>% 
mutate(receita_temp = receita) %>% 
mutate(dot_count = str_count(receita, '\\.')) %>% 
mutate(receita_temp = ifelse(dot_count == 3, 
                             gsub('\\.', '', as.factor(receita_temp)), 
                             gsub('\\,', '.',as.factor(receita_temp))
                             )) %>% 
mutate(receita_temp = ifelse(dot_count == 3,
                             gsub('\\,', '.',as.factor(receita_temp)),
                                  receita_temp)) %>% 
select(-c(dot_count, receita)) %>% 
rename(., receita = receita_temp)

标签: rregex

解决方案


我正在使用正则表达式和一些stringr函数来删除所有句点,除了后跟两位数字和字符串结尾的句点。这样,表示分隔的句点(如 in)3.811.786.009,24将被删除,但表示小数开头的句点(如 in)4821729985.03则不会。使用str_remove_all而不是str_remove让我不必担心重复删除匹配项或它的扩展程度。然后用句点替换剩余的逗号,并使其成为数字。

library(tidyverse)

df2 <- df %>%
  mutate(receita = str_remove_all(receita, "\\.(?!\\d{2,}$)") %>% 
           str_replace_all(",", ".") %>%
           as.numeric())

print(head(df2), digits = 12)
#>     n mesAno       receita
#> 1  97 1/2009 3812819062.06
#> 2  98 2/2009 4039362599.36
#> 3  99 3/2009 3652885587.18
#> 4 100 4/2009 3460247960.02
#> 5 101 5/2009 3465677403.12
#> 6 102 6/2009 3131903622.55

reprex 包(v0.2.0)于 2018 年 9 月 4 日创建。


推荐阅读