【发布时间】:2014-11-26 13:28:47
【问题描述】:
我正在尝试使用先前的包,但需要先考虑我的数据。我有一个数据表。有些列的因子少于 3 个(真/假,0/1),而其他列是连续变量。
看来我需要将表格分解如下
1) skip the key variables
2) leave the true/false columns alone
3) factor if there are less than 6 unique values
4) for more than 5 unique values, then factor by quantile
下面的代码示例满足了这些目标,并且 apriori 正在运行(现在)。
我收到一条警告,我无法理解。有人可以解释这个警告,以及如何纠正它吗?
library(data.table)
nSamples = 5000
set.seed(13)
dat <- data.table(id1=sample(seq(10000,10300),nSamples,replace=T),
id2=sample(100,nSamples,replace=T),
tfvar = sample(c(T,F),nSamples,replace=T),
contvar = runif(nSamples,1,2.3),
disvar = sample(c(1,2),nSamples,replace=T))
setkey(dat,id1,id2)
colsToFactor <- setdiff(names(dat),key(dat))
cdat <- dat
myfact<-function(x) {
if (typeof(x)== 'logical') {
return(x)
}
nux <- length(unique(x))
if (nux<3) {
cx <- factor(x)
} else {
cx <- cut2(x,g=5)
}
return(cx)
}
myprint<-function(xl) {
if (is.factor(xl)) {
print(levels(xl))
} else {
print('not a factor')
}
}
cdat[,(colsToFactor):=lapply(.SD, myfact),.SDcols=colsToFactor]
jnk<-cdat[, lapply(.SD, myprint)]
print(cdat)
这是输出
[1] "not a factor"
[1] "not a factor"
[1] "not a factor"
[1] "[1.00,1.27)" "[1.27,1.53)" "[1.53,1.79)" "[1.79,2.04)" "[2.04,2.30]"
[1] "1" "2"
id1 id2 tfvar contvar disvar
1: 10000 4 FALSE [1.53,1.79) 2
2: 10000 15 FALSE [2.04,2.30] 2
3: 10000 18 FALSE [1.53,1.79) 2
4: 10000 22 TRUE [1.00,1.27) 1
5: 10000 22 FALSE [1.00,1.27) 2
---
4996: 10300 81 FALSE [1.00,1.27) 2
4997: 10300 89 TRUE [1.79,2.04) 2
4998: 10300 89 TRUE [1.79,2.04) 1
4999: 10300 90 TRUE [1.79,2.04) 1
5000: 10300 93 FALSE [1.00,1.27) 1
警告信息是
Warning message:
In as.data.table.list(jval) :
Item 5 is of size 2 but maximum size is 5 (recycled leaving a remainder of 1 items)
如何摆脱这个警告?
【问题讨论】:
-
这里有五个问题(可能适合codereview.stackexchange.com)。对于 SO,为避免您的问题被关闭,最好将其分解。哪个任务导致了问题?你能找到一个重现问题的最小例子吗?一旦开始将问题模块化,就更有可能产生洞察力。
-
感谢您的反馈。我缩小了问题的范围。
-
正如您所建议的,尝试制作一个最小的示例确定了打印功能中的问题,然后导致以下解决方案。
标签: r unique data.table