我正在使用cut
将我的数据划分为多个二进制位,这会将结果二进制文件显示为(x1,x2]
。任何人都可以告诉我如何制作一个表达这些箱子作为箱子中点的新栏目?例如,使用以下数据框:
structure(list(x = c(1L, 4L, 6L, 7L, 8L, 9L, 12L, 18L, 19L),
y = 1:9), .Names = c("x", "y"), class = "data.frame", row.names = c(NA,
-9L))
我可以用
test$xRange <- cut(test$x, breaks=seq(0, 20, 5))
给予
x y xRange
1 1 1 (0,5]
2 4 2 (0,5]
3 6 3 (5,10]
4 7 4 (5,10]
5 8 5 (5,10]
6 9 6 (5,10]
7 12 7 (10,15]
8 18 8 (15,20]
9 19 9 (15,20]
但我需要的结果应该是:
x y xRange xMidpoint
1 1 1 (0,5] 2.5
2 4 2 (0,5] 2.5
3 6 3 (5,10] 7.5
4 7 4 (5,10] 7.5
5 8 5 (5,10] 7.5
6 9 6 (5,10] 7.5
7 12 7 (10,15] 12.5
8 18 8 (15,20] 17.5
9 19 9 (15,20] 17.5
我做了一些搜索,并在divide a range of values in bins of equal length: cut vs cut2遇到了一个类似的问题,提供了一个解决方案
cut2 <- function(x, breaks) {
r <- range(x)
b <- seq(r[1], r[2], length=2*breaks+1)
brk <- b[0:breaks*2+1]
mid <- b[1:breaks*2]
brk[1] <- brk[1]-0.01
k <- cut(x, breaks=brk, labels=FALSE)
mid[k]
}
但是当我在我的案例中尝试这个时,使用
test$xMidpoint <- cut2(test$x, 5)
它不会返回正确的中点。也许我在cut2
错误地输入了中断?谁能告诉我我做错了什么?
答案 0 :(得分:6)
除非我遗漏某些内容,否则这样的内容看起来有效:
brks = seq(0, 20, 5)
ints = findInterval(test$x, brks, all.inside = T)
#mapply(function(x, y) (x + y) / 2, brks[ints], brks[ints + 1]) #which is ridiculous
#[1] 2.5 2.5 7.5 7.5 7.5 7.5 12.5 17.5 17.5
(brks[ints] + brks[ints + 1]) / 2 #as sgibb noted
#[1] 2.5 2.5 7.5 7.5 7.5 7.5 12.5 17.5 17.5
(head(brks, -1) + diff(brks) / 2)[ints] #or using thelatemail's idea from the comments
#[1] 2.5 2.5 7.5 7.5 7.5 7.5 12.5 17.5 17.5
答案 1 :(得分:1)
我知道这是一个非常古老的问题,但这可能有助于未来的googlers。我写了一个函数,我称之为midcut,它可以切割数据并为我提供bin的中点。
midcut<-function(x,from,to,by){
## cut the data into bins...
x=cut(x,seq(from,to,by),include.lowest=T)
## make a named vector of the midpoints, names=binnames
vec=seq(from+by/2,to-by/2,by)
names(vec)=levels(x)
## use the vector to map the names of the bins to the midpoint values
unname(vec[x])
}
例如
test$midpoint=midcut(test$x,0,20,5)
> test
x y xRange midpoint
1 1 1 (0,5] 2.5
2 4 2 (0,5] 2.5
3 6 3 (5,10] 7.5
4 7 4 (5,10] 7.5
5 8 5 (5,10] 7.5
6 9 6 (5,10] 7.5
7 12 7 (10,15] 12.5
8 18 8 (15,20] 17.5
9 19 9 (15,20] 17.5
答案 2 :(得分:0)
无论您如何在“ cut”函数中指定断点(即,无论您是否提供断点向量或多个bin),都可以使用计算中间点的另一种方法是使用cut函数提供的标签文本。 / p>
get_midpoint <- function(cut_label) {
mean(as.numeric(unlist(strsplit(gsub("\\(|\\)|\\[|\\]", "", as.character(cut_label)), ","))))
}
test$xMidpoint <- sapply(test$xRange, get_midpoint)
请注意,这要求将cut函数中的“标签”参数设置为TRUE。