所有元素都相同,但向量不同?
Identical for all elements, but not identical vectors?
我有两个向量,一个来自 sqldf(),另一个来自 unique()。它们应该是相同的。当我使用 for 循环检查每个元素时,两个向量相同,但两个向量上的 identical() returns FALSE。有什么想法吗?
options(sqldf.driver = "SQLite")
options(gsubfn.engine = "R")
library(sqldf)
url <-"https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06pid.csv"
download.file(url, destfile = "CommunitySurvey.csv")
acs <- read.table("CommunitySurvey.csv", sep = ",", header = TRUE)
query <- as.matrix(sqldf("select distinct AGEP from acs"))
unique <- as.matrix(unique(acs$AGEP))
for (i in 1:dim(unique)[1]){
if (unique[i]!=query[i]){
print(unique[i])
print(query[i])
}
}
identical(query, unique)
原因是 'query' 中有 dimnames
的属性,而 'unique' 中没有。对于identical
到returnTRUE
,一切都应该是一样的
str(unique)
#int [1:91, 1] 43 42 16 14 29 40 15 28 30 4 ...
str(query)
# int [1:91, 1] 43 42 16 14 29 40 15 28 30 4 ...
# - attr(*, "dimnames")=List of 2
# ..$ : NULL
# ..$ : chr "AGEP"
一种选择是将 all.equal
与 check.attributes=FALSE
一起使用
all.equal(unique, query, check.attributes=FALSE)
#[1] TRUE
或者将dimnames
的'query'中的属性设置为NULL,然后使用identical
attr(query, "dimnames") <- NULL
identical(query, unique)
#[1] TRUE
我有两个向量,一个来自 sqldf(),另一个来自 unique()。它们应该是相同的。当我使用 for 循环检查每个元素时,两个向量相同,但两个向量上的 identical() returns FALSE。有什么想法吗?
options(sqldf.driver = "SQLite")
options(gsubfn.engine = "R")
library(sqldf)
url <-"https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06pid.csv"
download.file(url, destfile = "CommunitySurvey.csv")
acs <- read.table("CommunitySurvey.csv", sep = ",", header = TRUE)
query <- as.matrix(sqldf("select distinct AGEP from acs"))
unique <- as.matrix(unique(acs$AGEP))
for (i in 1:dim(unique)[1]){
if (unique[i]!=query[i]){
print(unique[i])
print(query[i])
}
}
identical(query, unique)
原因是 'query' 中有 dimnames
的属性,而 'unique' 中没有。对于identical
到returnTRUE
,一切都应该是一样的
str(unique)
#int [1:91, 1] 43 42 16 14 29 40 15 28 30 4 ...
str(query)
# int [1:91, 1] 43 42 16 14 29 40 15 28 30 4 ...
# - attr(*, "dimnames")=List of 2
# ..$ : NULL
# ..$ : chr "AGEP"
一种选择是将 all.equal
与 check.attributes=FALSE
all.equal(unique, query, check.attributes=FALSE)
#[1] TRUE
或者将dimnames
的'query'中的属性设置为NULL,然后使用identical
attr(query, "dimnames") <- NULL
identical(query, unique)
#[1] TRUE