【问题标题】:how to separate a column with a hyphen如何用连字符分隔列
【发布时间】:2021-09-19 13:20:17
【问题描述】:

这应该是一项简单的任务,但我遇到了障碍。

如何拆分第一列,得到两列的数值:

  require(xml2)
  require(rvest)
  require(janitor)
  require(tidyverse)
  require(janitor)
  
  raw_webpage <- read_html("https://www.ato.gov.au/Rates/Schedule-8---Statement-of-formulas-for-calculating-HELP,-SSL,-TSL-and-SFSS-components/")
  
  df1 <- html_table(raw_webpage, fill = TRUE)[[2]]
  
  df1 %>% clean_names() %>% 
    separate(weekly_earnings_x, into = c("one", "two"), sep = "\\-", convert = TRUE)

【问题讨论】:

标签: r dplyr


【解决方案1】:

除了最后一个之外,那些不是减号 (-)。

grepl("-", df1$`Weekly earnings (x)$`)
# [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
#[14] FALSE FALSE FALSE FALSE FALSE  TRUE

从数据框中复制分隔符并将其粘贴到 sep 参数中。

df1 %>% 
  clean_names() %>% 
  separate(weekly_earnings_x, into = c("one", "two"), 
           sep = "\\s*(–|-)\\s*", convert = TRUE)

#   one      two      component_rate_a_percent
#   <chr>    <chr>    <chr>                   
# 1 0        553.99   –                       
# 2 554.00   692.99   1.0                     
# 3 693.00   755.99   2.0                     
# 4 756.00   821.99   2.5                     
# 5 822.00   892.99   3.0                     
# 6 893.00   966.99   3.5                     
# 7 967.00   1,045.99 4.0                     
# 8 1,046.00 1,129.99 4.5                     
# 9 1,130.00 1,218.99 5.0                     
#10 1,219.00 1,312.99 5.5                     
#11 1,313.00 1,412.99 6.0                     
#12 1,413.00 1,518.99 6.5                     
#13 1,519.00 1,630.99 7.0                     
#14 1,631.00 1,749.99 7.5                     
#15 1,750.00 1,873.99 8.0                     
#16 1,874.00 2,009.99 8.5                     
#17 2,010.00 2,150.99 9.0                     
#18 2,151.00 2,300.99 9.5                     
#19 2,301.00 over     10.0       

您可能希望使用 readr::parse_number 将列转换为数字,因为它们中包含逗号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2015-09-26
    • 2015-08-02
    • 2016-06-04
    相关资源
    最近更新 更多