samedi 23 janvier 2021

Loop (FOR or WHILE) to extract rows into new dataframe based on categorical variable match

I need to search through all my data and extract certain columns for certain rows based on a categorical variable category. I don't think this should be too hard, but as a beginner I have spent a long time searching for similar answers and trying to implement into my code with no avail. This is what I have so far:

library(ukpolice)
crimes <- NULL
months <- list("2020-01","2020-02","2020-03","2020-04","2020-05")
for (i in months) {
  crimes <- rbind(crimes, ukc_crime_location(lat = 53.798520, lng = -1.548223, date = i))
}
crimes <- crimes[ -c(2,3,4,6,13) ]


crimes$category <- as.factor(crimes$category)
categories <- levels(crimes$category)
category <- crimes[, c("category", "id", "month","street_name")]
antisocialbehaviour <- data.frame(NULL)

for (k in (crimes)) {
  if (category$category[1] == "anti-social-behaviour") {
    antisocialbehaviour[k] <- category$id[1]
    k <- k + 1
  }
  category <- category[-1,] # remove first row
}

I have created my own data frame using the ukc_crime_location function. Essentially, I need to go through all the data and check whether the category in each row is anti-social-behaviour, and – if yes – add the columns id, month, and street name of this crime as a new row to the new data frame antisocialbehaviour, which I have defined. Currently I get the error message: Error in Summary.factor(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, : ‘min’ not meaningful for factors. I would really appreciate some help!

Aucun commentaire:

Enregistrer un commentaire