2017-03-07 3 views
1

나는 각 행이 개인이고 각 열이 질병 코드 인 R에 데이터 프레임을 가지고 있습니다. 각 세포에는 1 또는 0이 포함되어있어 개체가 질병에 걸렸는지 여부를 나타냅니다. 각 질병 코드 X에 대해 질병 X가없는 사람과 질병 X가없는 사람을 구분하고 싶습니다. 그런 다음 질병 X를 가진 환자의 질병 Y 또는 질병 Z가있는 상대 위험도를 계산하고자합니다. 여기에 샘플 데이터가 있습니다 나의 접근 방식 : 질병 0 개인이 또한 나의 질문은 4R의 행렬에서 모든 조건 쌍의 상대 위험을 계산하려면 어떻게해야합니까?

colMeans(filter(disease.df, disease0 == 1))/colMeans(filter(disease.df, disease0 != 1)) 

disease0 disease1 disease2 disease3 disease4 
     Inf 4.5000000 2.0000000 0.2857143 0.0000000 

을 통해 질병 1을 가지고

# generate reproducible dataframe with disease diagnoses 
set.seed(2) 
ID = c(0:19) 
disease0 = c(rbinom(10, 1, 0.0), rbinom(10, 1, 1.0)) 
disease1 = c(rbinom(10, 1, 0.1), rbinom(10, 1, 0.9)) 
disease2 = c(rbinom(10, 1, 0.5), rbinom(10, 1, 0.5)) 
disease3 = c(rbinom(10, 1, 0.9), rbinom(10, 1, 0.1)) 
disease4 = c(rbinom(10, 1, 1.0), rbinom(10, 1, 0.0)) 
(disease.df = data.frame(cbind(ID, disease0, disease1, disease2, disease3, disease4))) 
row.names(disease.df) = disease.df[ ,1] 
disease.df[ ,1] = NULL 
disease.df 

    disease0 disease1 disease2 disease3 disease4 
0   0  0  1  0  1 
1   0  0  0  1  1 
2   0  0  1  1  1 
3   0  0  0  1  1 
4   0  1  0  0  1 
5   0  1  0  1  1 
6   0  0  0  0  1 
7   0  0  0  1  1 
8   0  0  1  1  1 
9   0  0  0  1  1 
10  1  1  0  0  0 
11  1  1  0  0  0 
12  1  1  1  0  0 
13  1  1  1  1  0 
14  1  1  1  0  0 
15  1  1  1  0  0 
16  1  0  1  0  0 
17  1  1  0  1  0 
18  1  1  1  0  0 
19  1  1  0  0  0 

내가 상대 위험도를 계산하기 위해 다음 코드를 사용할 수있는 방법이있다 For 루프를 피하면서 벡터화 된 연산을 사용하거나 모든 5 가지 질병에 대해이를 수행하는 함수를 적용합니다. 이상적으로는 다음과 같은 테이블을 생성하고 싶습니다 :

  disease0 disease1 disease2 disease3 disease4 
diease0  Inf 4.5000000 2.0000000 0.2857143 0.0000000 
diease1 7.3636364  Inf 1.0227273 0.4090909 0.2045455 
diease2 1.8333333 1.0185185  Inf 0.6111111 0.5238095 
diease3 0.3055556 0.4583333 0.6111111  Inf 2.8518519 
diease4 0.0000000 0.2222222 0.5000000 3.5000000  Inf 
+0

Ronak의 아래 의견을보기 전에 위의 수정 사항을 저장했습니다. 혼란스러워서 죄송합니다. – Josh

답변

0

하지 최적의 솔루션은, 그러나 그것은 코드의 반복 라인에서 당신을 도울 수 있습니다. 내가 제대로 이해 한 경우

t(apply(df[-1], 2, function(x) { 
    temp = lapply(split(df[-1], x), colMeans) 
    temp[[2]]/temp[[1]] 
}) 
) 

#   disease0 disease1 disease2 disease3 disease4 
#disease0  Inf 4.5000000 2.0000000 0.2857143 0.0000000 
#disease1 7.3636364  Inf 1.0227273 0.4090909 0.2045455 
#disease2 1.8333333 1.0185185  Inf 0.6111111 0.5238095 
#disease3 0.3055556 0.4583333 0.6111111  Inf 2.8518519 
#disease4 0.0000000 0.2222222 0.5000000 3.5000000  Inf 

, 우리는 applylapply 통화의 조합으로이 작업을 수행 할 수 있습니다.

각 열에 대해 split의 데이터 프레임을 두 부분으로 나누고 (1과 0이있는 데이터 프레임) colMeans을 사용하여 모든 열의 평균을 찾고 두 개의 하위 목록을 요소별로 나눕니다.