Deleting specific rows from a data frame

后端 未结 3 1990
北荒
北荒 2020-12-03 12:49

I am working with some US govt data which has a lengthy list of cities and zip codes. After some work, the data is in the following format.

dat1 = data.frame         


        
3条回答
  •  执笔经年
    2020-12-03 13:17

    Here's one (slightly convoluted) approach that you may consider. First, create an identity column for each row. This will help with the subsetting. Secondly, create a vector of those id's that match your criteria. Finally, subset those id's out of your final data.

    The data you posted defaults to factors, not character data so I've accounted for that. If that's different than your actual data, you'll have to adjust accordingly. Also, when I converted the data to numeric, NAs are generated. A warning message is generated, but we can ignore that for this bit.

    #Generate an ID column
    dat4$id <- 1:nrow(dat4)
    
    #Create a vector of the id's that match your criteria'
    outliers <- dat4[as.character(dat4$tag) != "AlabamaZipCode" & !(is.na(as.numeric(as.character(dat4$keyword)))) , "id"]
    
    subset(dat4, !(id %in% outliers), select = 1:2)
                 keyword              tag
    1             Bremen       AlabamCity
    2              Brent       AlabamCity
    4        Chelsea, AL    AlabamaCityST
    5 Bailytown, Alabama AlabamaCityState
    7              54023   AlabamaZipCode
    8              54024   AlabamaZipCode
    

    Actually, you can shorten all of this to the following and avoid generating the id.

    dat4[!(as.character(dat4$tag) != "AlabamaZipCode" & !(is.na(as.numeric(as.character(dat4$keyword))))) , ]
    

提交回复
热议问题