Может кто-нибудь объяснить, что означают эти строки кода? - PullRequest
1 голос
/ 01 марта 2020

Я пытался найти способ создать график рассеяния с интенсивностью цвета, которая указывает на плотность точек, нанесенных на график в области (это большой набор данных с большим количеством совпадений). Я нашел эти строки кода, которые позволяют мне сделать это, но я хочу убедиться, что я действительно понимаю, что на самом деле делает каждая строка. Заранее спасибо:)

get_density <- function(x, y, ...){
  dens <- MASS::kde2d(x, y, ...)
  ix <- findInterval(x, dens$x)
  iy <- findInterval(y, dens$y)
  ii <- cbind(ix, iy)
  return(dens$z[ii])
}

set.seed(1)

dat <- data.frame(x = subset2$conservation.phyloP, y = subset2$gene.expression.RPKM)
dat$density <- get_density(dat$x, dat$y, n = 100)  

1 Ответ

3 голосов
/ 01 марта 2020

Ниже приведена функция с некоторыми пояснительными комментариями, дайте мне знать, если что-то все еще сбивает с толку:

# The function "get_density" takes two arguments, called x and y
# The "..." allows you to pass other arguments 
get_density <- function(x, y, ...){ 

# The "MASS::" means it comes from the MASS package, but makes it so you don't have to load the whole MASS package and can just pull out this one function to use. 
# This is where the arguments passed as "..." (above) would get passed along to the kde2d function
dens <- MASS::kde2d(x, y, ...)
# These lines use the base R function "findInterval" to get the density values of x and y
ix <- findInterval(x, dens$x)
iy <- findInterval(y, dens$y)
# This command "cbind" pastes the two sets of values together, each as one column
ii <- cbind(ix, iy)
# This line takes a subset of the "density" output, subsetted by the intervals above
return(dens$z[ii])
}  

# The "set.seed()" function makes sure that any randomness used by a function is the same if it is re-run (as long as the same number is used), so it makes code more reproducible
set.seed(1)

dat <- data.frame(x = subset2$conservation.phyloP, y = subset2$gene.expression.RPKM)
dat$density <- get_density(dat$x, dat$y, n = 100)  

Если ваш вопрос касается самой функции MASS::kde2d, возможно, было бы лучше переписать этот StackOverflow вопрос, чтобы отразить это!

Похоже, что та же самая функция включена в ggplot2 метод, описанный здесь , поэтому, если вы переключитесь на создание своего графика с помощью ggplot2, вы можете дать ей попытка.

...