我有一个非常大的变量数据集,我需要根据邮政编码的前三个数字进行分组。我不确定如何做到这一点,并感谢您提供的任何帮助。
如何将此示例dput子集化以删除所有以721开头的邮政编码。请注意,由于邮政编码大于721谢谢,我不能简单地执行大于(>)的操作!
dput:
data <- structure(list(state = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("AR",
"IL", "MO"), class = "factor"), zip = c(72003L, 72042L, 72073L,
72166L, 72038L, 72055L, 72160L, 72026L, 72048L, 72140L, 72003L,
72042L, 72073L, 72166L, 72038L, 72055L, 72160L, 72026L, 72048L,
72140L)), .Names = c("state", "zip"), row.names = c(NA, 20L), class = "data.frame")
数据:
state zip
1 AR 72003
2 AR 72042
3 AR 72073
4 AR 72166
5 AR 72038
6 AR 72055
7 AR 72160
8 AR 72026
9 AR 72048
10 AR 72140
11 AR 72003
12 AR 72042
13 AR 72073
14 AR 72166
15 AR 72038
16 AR 72055
17 AR 72160
18 AR 72026
19 AR 72048
20 AR 72140
答案 0 :(得分:5)
您可以尝试substr
data[substr(data$zip, 1,3)!=721,]
或使用data.table
library(data.table)
setDT(data)[substr(zip,1,3)!=721]
或dplyr
library(dplyr)
data %>%
filter(substr(zip, 1,3)!=721)
或使用extract
tidyr
library(tidyr)
extract(data, zip, 'zip1', '(...).*', FALSE) %>%
filter(zip1!=721) %>%
select(-zip1)