基于条件,抖动指向不同的量

时间:2016-08-15 12:20:11

标签: r plot visualization jitter

我有一个具有离散X轴值和大量Y值的数据集。我还有一个单独的向量,测量X轴值的不确定性;这种不确定性在X轴上变化。我想将我的X轴值抖动一个与该不确定性度量成比例的量。使用循环执行此操作很简单但很麻烦;我正在寻找一个有效的解决方案。

可重复的例子:

#Create data frame with discrete X-axis values (a)
dat <- data.frame(a = c(rep(5, 5), rep(15,5), rep(25,5)), 
                  b = c(runif(5, 1, 2), runif(5, 2, 3), runif(5, 3, 4)))

#Plot raw, unjittered data
plot(dat$b ~ dat$a, data = dat, col = as.factor(dat$a), pch = 20, cex = 2)

enter image description here

#vector of uncertainty estimates
wid_vec <- c(1,10,3)

#Ugly manual jittering, not feasible for large datasets but 
#produces the desired result
dat$a_jit <- c(jitter(rep(5, 5), amount = 1), 
                jitter(rep(15, 5), amount = 10), 
                jitter(rep(25, 5), amount = 3))

plot(dat$b ~ dat$a_jit, col = as.factor(dat$a), pch = 20, cex = 2)

enter image description here

#Ugly loop solution, also works

newdat <- data.frame()
a_s <- unique(dat$a)

for (i in 1:length(a_s)){
  subdat       <- dat[dat$a == a_s[i],]
  subdat$a_jit <- jitter(subdat$a, amount = wid_vec[i])
  newdat <- rbind(newdat, subdat)
}

plot(newdat$b ~ newdat$a_jit, col = as.factor(newdat$a), pch = 20, cex = 2)

#Trying to make a vectorized solution, but this of course does not work.

jitter_custom <- function(x, wid){
  j <- x + runif(length(x), -wid, wid)
  j
}

#runif() does not work this way, this is shown to indicate the direction 
#I've been attempting

基本上,我需要按条件拆分dat,调用wid_vec向量中的相关条目,然后通过基于wild_vec值修改dat条目来创建新列。听起来应该有一个优雅的dplyr解决方案,但它现在没有我。

感谢所有建议!

1 个答案:

答案 0 :(得分:1)

作为

的替代方案
set.seed(1)
dat$a_jit <- c(jitter(rep(5, 5), amount = 1), 
                jitter(rep(15, 5), amount = 10), 
                jitter(rep(25, 5), amount = 3))

你可以做到

set.seed(1)
x <- with(dat, jitter(a, amount=setNames(c(1,10,3), unique(a))[as.character(a)]))

结果是一样的:

identical(x, dat$a_jit)
# [1] TRUE

如果您希望警告消失,可以在suppressWarnings()周围包裹jitter(...),或使用with(dat, mapply(jitter, x=a, amount=setNames(c(1,10,3), unique(a))[as.character(a)]))之类的内容。