【问题标题】:How do I fix the error "Error in match(x, table, nomatch = 0L) : 'match' requires vector arguments"?如何修复错误“匹配错误(x,表,nomatch = 0L):'匹配'需要向量参数”?
【发布时间】:2021-07-02 09:38:13
【问题描述】:

当我运行这段代码时

url <- "https://github.com/midas-network/covid19-scenario-modeling-hub/blob/master/data-processed/Karlen-pypm/2021-05-30-Karlen-pypm.zip?raw=true"
temp <- tempfile()
download.file(url, temp)
karlen_model <- read.csv(unz(temp, "2021-05-30-Karlen-pypm.csv")) 
unlink(temp)

#karlen_model <- fread("/Karlen-pypm/2021-05-30-Karlen-pypm.csv")
karlen_ca <- karlen_model[location %in% "06"]

我得到错误:

"Error in match(x, table, nomatch = 0L) : 
  'match' requires vector arguments"

我尝试了这个解决方法:

karlen_ca <- karlen_model[location == "06"]

但得到另一个错误:

Error in location == "06" : 
  comparison (1) is possible only for atomic and list types

请注意:

  1. 由于我正在下载公开可用的数据,因此该示例是可重现的;
  2. 对象karlen_model是一个数据框;和
  3. class(karlen_model$location) 返回factor

非常感谢, 大卫

【问题讨论】:

    标签: r


    【解决方案1】:

    您尝试的语法是有效的 data.table 语法,但不是有效的基本 R 语法。

    在基础 R 中,您需要使用 $[[ 显式引用数据框列。

    所以这两种方法都可以 -

    karlen_ca <- karlen_model[karlen_model$location %in% "06", ]
    

    或者

    karlen_ca <- karlen_model[karlen_model$location == "06", ]
    

    您的代码可以使用 with,但需要在行选择后添加逗号。

    karlen_ca <- with(karlen_model, karlen_model[location == "06", ])
    

    【讨论】:

    • 谢谢@Ronak Shah。不过,只有一件事:data.table 包已加载(我仔细检查过)。那么为什么我的代码不起作用呢?
    • @dbcrow 虽然,您已经加载了data.table,但karlen_model 不是data.table 对象。使用setDT(karlen_model),然后尝试karlen_ca &lt;- karlen_model[location == "06"]
    【解决方案2】:

    您可以在基础 R 中使用子集:

    # some data as an example
    dat <- data.frame(something = letters[1:4], 
                      location = c("06", "03", "01", "06"))
    
    # use subset
    subset(dat, location == "06")
    #R>   something location
    #R> 1         a       06
    #R> 4         d       06
    
    # or with the the new pipe in R 4.1.0
    dat |> subset(location == "06")
    #R>   something location
    #R> 1         a       06
    #R> 4         d       06
    

    【讨论】:

    • 非常感谢,@Benjamin Christoffersen。这是我第一次听说 R 4.1.0 中的新管道。
    【解决方案3】:

    我确实找到了一种成功的解决方法——即,使用 dplyr 的过滤器:

    karlen_ca <- karlen_model %>% filter(location == "06")
    

    所以,这更像是一个好奇的问题,但为什么前两行(使用括号和基数 R)都不起作用?如何修复它们,尤其是在基本 R 框架内?

    非常感谢, 大卫

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多