David Crow
David Crow

Reputation: 163

How do I fix the error "Error in match(x, table, nomatch = 0L) : 'match' requires vector arguments"?

When I run this code

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"]

I get the error:

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

I tried this workaround:

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

but get another error:

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

Please note that:

  1. Since I'm downloading publicly available data, the example is reproducible;
  2. The object karlen_model is a data frame; and
  3. class(karlen_model$location) returns factor.

Many thanks, David

Upvotes: 1

Views: 6350

Answers (3)

Benjamin Christoffersen
Benjamin Christoffersen

Reputation: 4841

You can use subset in base 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

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 389295

The syntax that you are trying is a valid data.table syntax but not a valid base R syntax.

In base R, you need to refer the column of dataframe explicitly using $ or [[.

So either of these will work -

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

Or

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

Your code would work with with but it will need a comma added after row selection.

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

Upvotes: 3

David Crow
David Crow

Reputation: 163

I did find one successful workaround--viz., using dplyr's filter:

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

So, it's more a matter of curiosity than anything, but why don't either of the first two lines (using brackets and base R) work? How can they be fixed, especially within a base R framework?

Gratefully, David

Upvotes: 0

Related Questions