【问题标题】:Use mutate_at to change multiple column types使用 mutate_at 更改多个列类型
【发布时间】:2016-09-01 19:45:07
【问题描述】:

我正在尝试使用dplyr 来整理数据集。我要更改的列有一个字符串,它实际上是一个双精度但用逗号而不是小数点。到目前为止,我得到了这个:

presupuesto_2016 <- read_csv( "http://datos.gob.ar/dataset/89f1a2dd-ad79-4211-87b4-44661d81ac0d/resource/84e23782-7d52-4724-a4ba-2f9621fa5f4e/download/presupuesto-2016.csv")

names(presupuesto_2016) <- str_replace(names(presupuesto_2016), "\uFEFF", "")

presupuesto_2016 %>%
  mutate_at(starts_with("monto_"),
            str_replace, pattern = ",", replacement = "\\.") %>% 
  mutate_at(starts_with("monto_"), funs(as.numeric))

但这设法将每一列更改为数字。我在这里做错了什么?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    如果你想使用mutate_at和列选择辅助函数,它们必须被包裹在vars函数中才能正常工作,看看?mutate_at

    presupuesto_2016 %>%
      mutate_at(vars(starts_with("monto_")),
      #         ^^^ 
                str_replace, pattern = ",", replacement = "\\.") %>% 
      mutate_at(vars(starts_with("monto_")), funs(as.numeric))
      #         ^^^ 
    

    【讨论】:

      【解决方案2】:

      为什么不直接做:

      URL <- "http://datos.gob.ar/dataset/89f1a2dd-ad79-4211-87b4-44661d81ac0d/resource/84e23782-7d52-4724-a4ba-2f9621fa5f4e/download/presupuesto-2016.csv"
      presupuesto_2016 <- read_csv(URL, locale=locale(decimal_mark=","))
      

      另外,我建议这样做:

      fil <- basename(URL)
      if (!file.exists(fil)) download.file(URL, fil)
      presupuesto_2016 <- read_csv(fil, locale=locale(decimal_mark=","))
      

      以节省您和该网站的带宽,加快未来的处理速度并确保在该网站离线或您离线的情况下可重现。

      【讨论】:

      • 主要是因为我在寻找类似 @​​987654323@ 的东西,比如 read.csv。但我知道我应该仔细阅读帮助文件。
      猜你喜欢
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      相关资源
      最近更新 更多