We can use dplyr::group_by
, then use summarise
:
library(dplyr)
data %>%
group_by(core_x,core_y) %>%
summarise(result = sum(density[expr_phenotype %in% c(4,68)])/
sum(density[expr_phenotype %in% c(0,4,64,68)]) * 100)
## A tibble: 3 x 3
## Groups: core_x [1]
# core_x core_y result
# <int> <int> <dbl>
#1 1 1 39.8
#2 1 2 39.1
#3 1 3 51.8
Data (Obtained by OCR, please forgive errors)
data <- structure(list(core_x = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L), core_y = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L), core = structure(c(1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L), .Label = c("1--1", "1--2",
"1--3"), class = "factor"), xX = structure(c(1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L), .Label = "Cc", class = "factor"), phenotype = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "CD163", class = "factor"),
expr_phenotype = c(0L, 4L, 64L, 68L, 0L, 4L, 64L, 68L, 0L,
4L), count = c(510L, 334L, 1L, 4L, 186L, 116L, 1L, 3L, 196L,
210L), density = c(451L, 295L, 1L, 4L, 164L, 103L, 1L, 3L,
173L, 186L)), row.names = 3:12, class = "data.frame")