难以正确清理薪资数据(生成NA)

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

我正在尝试清理下面小标题的工资栏:

最低工资 最高工资
65K 75K
65K 75K
65K 75K
56.3K 90.8K
61.7K 105K
45,360 84,240

我不知道如何将上面两个工资栏做成只有数字的方式(没有标点符号,没有“K”字符)。

我尝试了3种不同的方法。这三种情况的结果都是一样的。

1)

    yearly %>%
        mutate(min_salary = case_when(grepl("K", min_salary) ~ 
        as.numeric(gsub("[^0-9.]", "", min_salary)) * 1000, TRUE ~ 
        as.numeric(min_salary)), 
        max_salary = case_when( grepl("K", max_salary) ~ 
        as.numeric(gsub("[^0-9.]", "", max_salary)) * 1000, TRUE ~ 
        as.numeric(max_salary)
        )
         )

2)

    yearly %>%
        mutate( min_salary = ifelse(grepl("K", min_salary), 
        as.numeric(gsub("[^0-9.]", "", min_salary)) * 1000, 
        as.numeric(min_salary)),
        max_salary = ifelse(grepl("K", max_salary), as.numeric(gsub(" 
        [^0-9.]", "", max_salary)) * 1000, as.numeric(max_salary)))

3)

yearly %>%
    mutate(min_salary = ifelse(str_detect(min_salary, "K"),
    as.numeric(gsub("[^0-9.]", "", min_salary)) * 1000,
    as.numeric(min_salary)),
    max_salary = ifelse(str_detect(max_salary, "K"),
    as.numeric(gsub("[^0-9.]", "", max_salary)) * 1000,
    as.numeric(max_salary)))

结果

一点点

最低工资 最高工资
65000 75000
65000 75000
65000 75000
56300 90800
61700 105000
不适用 不适用

ℹ 还有 1,776 行 ℹ 使用

print(n = ...)
查看更多行 警告信息:
mutate()
中有 2 个警告。 第一个警告是: ℹ 在争论中:
min_salary = ifelse(...)
。 由
ifelse()
中的警告引起: !通过强制引入的 NA ℹ 运行 dplyr::last_dplyr_warnings() 以查看剩余的 1 个警告。

如何不生成“NA”? NA 行是原始小标题中没有“K”的行。

r if-statement case data-cleaning na
1个回答
0
投票

您可以创建一个快速帮助函数,然后跨列应用它。我添加了

tidyverse
基本 R 选项:

示例数据

yearly <- read.table(text = "min_salary max_salary
65K 75K
65K 75K
65K 75K
56.3K   90.8K
61.7K   105K
45,360  84,240", header = TRUE)

代码:

quickfun <- function(x){
  yy <- readr::parse_number(x)
  ifelse(stringr::str_detect(x, "K"), yy*1e3, yy)
}

# in base R
quickfun_base <- function(x){
  yy <- as.numeric(gsub("\\D", "", x))
  ifelse(grepl("K", x), yy*1e3, yy)
}

将其应用到您的

dplyr
链中:

yearly %>%
  mutate(across(c(min_salary, max_salary), ~quickfun(.x)))

#  min_salary max_salary
# 1      65000      75000
# 2      65000      75000
# 3      65000      75000
# 4      56300      90800
# 5      61700     105000
# 6      45360      84240

在基础 R 中使用

lapply

yearly[c("min_salary","max_salary")] <- lapply(yearly[c("min_salary","max_salary")], quickfun)

#  min_salary max_salary
# 1      65000      75000
# 2      65000      75000
# 3      65000      75000
# 4      56300      90800
# 5      61700     105000
# 6      45360      84240
© www.soinside.com 2019 - 2024. All rights reserved.