我有一个带有间隔定义的数据框:
ints <- read.table(header=T, sep=";", stringsAsFactors = FALSE, na.strings = 'NA', text="
minValue;minOperato;maxValue;maxOperator;class
3914;>=;NA;NA;[3914,Inf)
NA;NA;1373;<;[ -Inf,1373)
1373;>=;1806;<;[1373,1806)
2777;>=;3914;<;[2777,3914)
1806;>=;2777;<;[1806,2777)
")
第二个数据帧带有值x
和二进制变量y
:
sd <- data.frame(x = runif(1000) * 5000, y = as.integer(runif(1000) > .5))
现在,我想获取sd
每个间隔的数据帧中的零和一的数目,并将结果合并到ints
数据帧中。
我以为我会用cut
:
breaks <- c(-Inf, ints$minValue[order(ints$minValue)], Inf)
breaks <- breaks[!is.na(breaks)]
out <- as.data.frame.matrix(table(cut(sd$x, breaks, right = FALSE), sd$y))
不幸的是,在时间间隔out
不与我间隔匹配ints
的数据帧(被不同地表示),所以我不能加入out
到ints
。
我知道我可能可以使用sqldf
package或ints$x
在某些循环中重新编码来生成一些sql ,但这会很慢。
一种解决方案是用一个简单的id(一个序列)替换您的间隔。应该对int和out.data.frames进行此操作。每个ID标识一个间隔。一旦执行此操作,合并就很简单了。
## first I extract the intevals from ints in ordered manner
id <- !is.na(ints$minValue)&!is.na(ints$maxValue)
class_factor <-
c(ints$class[which(is.na(ints$minValue))],
ints$class[id][order(ints$minValue[id])],
ints$class[which(is.na(ints$maxValue))])
## add an id column that identify each interval in ints data.frame
ints <- merge(data.frame(class=class_factor,id = seq_along(class_factor)),ints)
## Do same thing in out uisng lables=FALSE as a cut argument
out <- as.data.frame.matrix(table(cut(sd$x, breaks, right = FALSE,
labels=FALSE), sd$y)) ## here the trick
## merge ints and out
merge(out,ints,by.x=0,by.y="id")
# Row.names 0 1 class minValue minOperato maxValue maxOperator
# 1 1 132 146 [ -Inf,1373) NA <NA> 1373 <
# 2 2 45 38 [1373,1806) 1373 >= 1806 <
# 3 3 98 99 [1806,2777) 1806 >= 2777 <
# 4 4 98 110 [2777,3914) 2777 >= 3914 <
# 5 5 125 109 [3914,Inf) 3914 >= NA <NA>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句