내 summarise()
함수 의 출력을 원하는 3 개의 행렬로 바꾸는 가장 짧은 방법은 무엇 일까요?
z <- "group y1 y2
1 1 2 3
2 1 3 4
3 1 5 4
4 1 2 5
5 2 4 8
6 2 5 6
7 2 6 7
8 3 7 6
9 3 8 7
10 3 10 8
11 3 9 5
12 3 7 6"
dat <- read.table(text = z, header = T)
dat %>%
group_by(group) %>%
summarise(cov = cov(y1, y2) * (n() - 1),
across(c(y1, y2), ~ var(.) * (n() - 1)))
# group DV1 DV2 cov
#1 1 6 2 0
#2 2 2 2 -1
#3 3 6.8 5.2 2.6
group1 = matrix(c(6,0,0,2),2)
group2 = matrix(c(2,-1,-1,2),2)
group3 = matrix(c(6.8,2.6,2.6,5.2),2)
우리는 훨씬 더 간단한 방법으로 이것을 할 수 있습니다. "그룹"으로 그룹화 한 후, 생성 list
컬럼에 summarise
복용으로 cov
의 matrix
의해 생성을 cbind
곱함으로써 다음, 'Y2'을 ', Y1'를 보내고, 및n() - 1
out <- dat %>%
group_by(group) %>%
summarise(mat1 = list(cov(cbind(y1, y2)) * (n() - 1)),
.groups = 'drop')
-산출
out$mat1
#[[1]]
# [,1] [,2]
#[1,] 6 0
#[2,] 0 2
#[[2]]
# [,1] [,2]
#[1,] 2 -1
#[2,] -1 2
#[[3]]
# [,1] [,2]
#[1,] 6.8 2.6
#[2,] 2.6 5.2
또는 이것은 group_split
및map
library(purrr)
dat %>%
group_split(group, .keep = FALSE) %>%
map(~ cov(.x) * (nrow(.x) - 1))
에서 base R
, 우리가 사용할 수 있습니다split
lapply(split(dat[c('y1', 'y2')], dat$group),
function(x) cov(x) * (nrow(x) - 1))
세 개의 '그룹'개체를 만들어야하는 경우 list2env
library(stringr)
deframe(out) %>%
set_names(str_c('group', seq_along(.))) %>%
list2env(.GlobalEnv)
group1
# [,1] [,2]
#[1,] 6 0
#[2,] 0 2
group2
# [,1] [,2]
#[1,] 2 -1
#[2,] -1 2
group3
# [,1] [,2]
#[1,] 6.8 2.6
#[2,] 2.6 5.2
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다