gpt4 book ai didi

r - data.table 中的列类有什么限制?

转载 作者:行者123 更新时间:2023-12-02 00:28:45 26 4
gpt4 key购买 nike

更新 此问题与 data.table 1.8.0 及更高版本不再相关。来自新闻文件:

character columns are now allowed in keys and are preferred to factor. data.table() and setkey() no longer coerce character to factor. Factors are still supported. Implements FR#1493, FR#1224 and (partially) FR#951.

原始问题

我尝试加入两个 data.tables。但是,连接的成功取决于我用来匹配 data.tables 的列的类。更准确地说,列似乎不应该具有“字符”类。我不太明白原因,但我确定我在这里遗漏了一些明显的东西。因此,非常感谢您的帮助。

这是一个例子:

#Objective: Select all rows from DT for which Region=="US", Year >= 5 & Year<=8, Cat="A"                 
library(data.table)
#Set-up data.table DT
DT <- data.table(Year=1:20, value=rnorm(20), Region=c(rep("US", 10), rep("EU", 10)), Cat=c(rep("A", 7), rep("B", 7), rep("C", 6)))
setkey(DT, Region, Cat, Year)
#Set-up data.table int_DT to join with DT
years <- 5:8
df <- data.frame(Region=c("US", "EU"), Categ=c("A", "B"))
int_DT <- J(cbind(df[1, ], years))
#Join them: Works like a charm!
DT[int_DT]

#Let's assume that for any reason the columns in df are of class "character"
df$Region <- as.character(df$Region)
df$Categ <- as.character(df$Categ)
#Rebuild int_DT
int_DT <- J(cbind(df[1, ], years))
DT[int_DT]
#Error in `[.data.table`(DT, int_DT) :
# unsorted column Region of i is not internally type integer.

#OK, maybe the problem is that the column classes in DT are factors, so change those:
DT[, Cat:=as.character(Cat)]
DT[, Region:=as.character(Region)]

DT[int_DT]
#Error in `[.data.table`(DT, int_DT) :
# When i is a data.table, x must be sorted to avoid a vector scan of x per row of i

还是不行。为什么?限制是什么?我想念什么?附加信息:我在平台上使用 data.table 1.6.6 和 R 版本 2.13.2 (2011-09-30):x86_64-pc-linux-gnu(64 位)。

最佳答案

您不需要连接操作来获得您想要的结果。你说:'目标:从 DT 中选择 Region=="US", Year >= 5 & Year<=8, Cat="A"' 的所有行'

DT[Region=="US" & Year>=5 & Year <= 8 & Categ=="A"]
Year value Region Categ
[1,] 5 -0.18631697 US A
[2,] 6 1.40059083 US A
[3,] 7 0.01848557 US A

但是要回答你关于列类的问题。我设法让这段代码起作用,它基本上反射(reflect)了你上面的代码:

> setkey(DT, Region, Categ, Year)
> df <- data.frame(Region=c("US", "EU"), Categ=c("A", "B"))
> dt2 <- data.table(data.frame(df[1, ], Year=5:8))
Warning message:
In data.frame(df[1, ], Year = 5:8) :
row names were found from a short variable and have been discarded
> dt1[dt2]
Region Categ Year value
[1,] US A 5 -0.5565422
[2,] US A 6 -0.1805841
[3,] US A 7 1.4474403
[4,] US A 8 NA

相同,character列类:

df$Region <- as.character(df$Region)
df$Categ <- as.character(df$Categ)
#Rebuild int_DT
dt2 <- J(cbind(df[1, ], Year=5:8))

Warning message:
In data.frame(..., check.names = FALSE) :
row names were found from a short variable and have been discarded

setkey(dt2, Region)
dt1[dt2]
Region Year value Categ Categ.1 Year.1
US 1 1.20152558 A A 5
US 2 1.89391079 A A 5
US 3 -1.76022634 A A 5
US 4 0.92454680 A A 5
US 5 -0.55654217 A A 5
...
snip
...
US 9 0.67936243 B A 8
US 10 -0.09355764 B A 8

关于r - data.table 中的列类有什么限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7828428/

26 4 0