Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R中的子集使用%s和==运算符返回不同的值_R_Subset - Fatal编程技术网

R中的子集使用%s和==运算符返回不同的值

R中的子集使用%s和==运算符返回不同的值,r,subset,R,Subset,我是R新手,正在学习几种数据子集的方法。在zipcode设置的餐厅数据(RestData)中,使用下面的匹配数的差异让我感到困惑 > nrow(restData[restData$zipCode %in% c("21212","21213"),]) # [1] 59 > nrow(restData[restData$zipCode == c("21212","21213"),]) # [1] 26 >Warning message: In restData$zipCode =

我是R新手,正在学习几种数据子集的方法。在zipcode设置的餐厅数据(RestData)中,使用下面的匹配数的差异让我感到困惑

> nrow(restData[restData$zipCode %in% c("21212","21213"),])
# [1] 59
> nrow(restData[restData$zipCode == c("21212","21213"),])
# [1] 26

>Warning message:
In restData$zipCode == c("21212", "21213") :
 longer object length is not a multiple of shorter object length
我正在使用下面的数据集,以防您想要复制

fileURL <- "https://data.baltimorecity.gov/api/views/k5ry-ef3g/rows.csv?accessType=DOWNLOAD"
download.file(fileURL, destfile = "./Rdata/restaurants.csv", method = "curl")
restData <- read.csv("./Rdata/restaurants.csv")

fileURL您得到的答案不一样,因为这两行的答案不一样!如果要索引邮政编码为
“21212”
“21213”
RestData
位置,则第一个是正确的。有关更多详细信息,请参见
?%in%”

在第二行中,重要的是要知道,当二进制操作需要时,R将“循环”较短向量的元素。例如,
1:6+1:2
将循环第二个向量(长度为2)使其成为长度为6的向量,因此您确实需要
1:6+rep(1:2,长度=6)
。在你的情况下,你正在做什么

restData$zipCode == rep(c("21212", "21213"), length=nrow(restData))

比较是逐元素进行的。因此,它告诉您奇数位置是
“21212”
还是偶数位置是
“21213”
。您得到的警告很重要,因为它告诉您正在比较奇数长度的向量和偶数长度的向量。在某些情况下,回收是有用的,例如
restData$zipCode[c(TRUE,FALSE)]
将仅检索奇数位置

你做过搜索吗?你也可以做一些实验:
x=1:5;x%以%c(1,3)表示;x==c(1,3);x==c(3,1);x==1;x==3;x==1 | x==3;x[x%c(1,3)];我明白你的意思,谢谢