2014-01-27 3 views
2

아래의 재현 가능 (잘라 내기 + 붙여 넣기) 예제를 참조하십시오. 실제 데이터 세트는 11000 명에 대해 4000 건 이상의 일련의 관찰 결과가 있습니다. 나는 "질병"변수의 특정 값의 첫 번째 발생에 해당하는 "약물"변수 X, Y, Z 등의 수를 보여주는 열 A, B, C 등을 생성해야합니다. 숫자는 특정 약물 (시작, 중지, 용량 증가 등)으로 취한 행동을 나타냅니다. "질병"변수는 발화 및 완화를 포함한 많은 단계의 질병에서 발병 여부를 나타냅니다. 예를 들어다른 데이터 프레임의 값으로 저장된 열 이름을 기반으로 한 데이터 프레임의 조회 값

:

Animal <- c("aardvark", "1", "cheetah", "dromedary", "eel", "1", "bison", "cheetah", "dromedary",  
"eel") 
Plant <- c("apple_tree", "blossom", "cactus", "1", "bronze", "apple_tree", "bronze", "cactus",  
"dragonplant", "1") 
Mineral <- c("amber", "bronze", "1", "bronze", "emerald", "1", "bronze", "bronze", "diamond",  
"emerald") 
Bacteria <- c("acinetobacter", "1", "1", "d-strep", "bronze", "acinetobacter", "bacillus", 
"chlamydia", "bronze", "enterobacter") 
AnimalDrugA <- c(1, 11, 12, 13, 14, 15, 16, 17, 18, 19) 
AnimalDrugB <- c(20, 1, 22, 23, 24, 25, 26, 27, 28, 29) 
PlantDrugA <- c(301, 302, 1, 304, 305, 306, 307, 308, 309, 310) 
PlantDrugB <- c(401, 402, 1, 404, 405, 406, 407, 408, 409, 410) 
MineralDrugA <- c(1, 2, 3, 4, 1, 6, 7, 8, 9, 10) 
MineralDrugB <- c(11, 12, 13, 1, 15, 16, 17, 18, 19, 20) 
BacteriaDrugA <- c(1, 2, 3, 4, 5, 6 , 7, 8, 9, 1) 
BacteriaDrugB <- c(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) 
dummy_id <- c(1001, 2002, 3003, 4004, 5005, 6006, 7007, 8008, 9009, 10101) 


Elements <- data.frame(dummy_id, Animal, Plant, Mineral, Bacteria, AnimalDrugA, AnimalDrugB,   
PlantDrugA, PlantDrugB, MineralDrugA, MineralDrugB, BacteriaDrugA, BacteriaDrugB) 
ds <- Elements[,order(names(Elements))] 
ds #Got it in alphabetical order... The real data set will be re-ordered chronologically 


#Now I want the first occurrence of the word "bronze" for each id 
# for each subject 1 through 10. (That is, "bronze" corresponds to start of disease flare.) 
first.bronze <- colnames(ds)[apply(ds,1,match,x="bronze")] 
first.bronze 

#Now, I want to find the number in the DrugA, DrugB variable that corresponds to the first    
#occurrence of bronze. 
#Using the alphabetically ordered data set, the answer should be: 
#dummy_id DrugA DrugB 
#1...  NA NA 
#2...  2 12 
#3...  NA NA 
#4...  4  1 
#5...  5  6 
#6... NA NA 
#7... 7  17 
#8... 8  18 
#9... 9  2 
#10... NA NA 
#Note that all first occurrences of "bronze" 
# are in Mineral or Bacteria. 
#As a first step, join first.bronze to the ds 
ds$first.bronze <- first.bronze 
ds 

#Make a new ds where those who have an NA for first.bronze are excluded: 
ds2 <- ds[complete.cases(ds$first.bronze),] 
ds2 


# Create a template data frame 
out <- data.frame(matrix(nr = 1, nc = 3)) 
colnames(out) <- c("Form Number", "DrugA", "DrugB") # Gives correct column names 
out 

#Then grow the data frame...yes I realize potential slowness of computation 
test <- for(i in ds2$first.bronze){ 
    data <- rbind(colnames(ds2)[grep(i, names(ds2), ignore.case = FALSE, fixed = TRUE)]) 
    colnames(data) <- c("Form Number", "DrugA", "DrugB") # Gives correct column names 
    out <- rbind(out, data) 
} 
out 

#Then delete the first row of NAs 
out <- na.omit(out) 
out 

#Then add the appropriate dummy_ids 
dummy_id <- ds2$dummy_id 
out_with_ids <- as.data.frame(cbind(dummy_id, out)) 
out_with_ids 

는 지금은 붙어입니다. 나는 ds2의 컬럼 이름을 out_with_ids 데이터 세트의 Drug A, Drug B 값으로 나열했습니다. 스택 오버플로를 통해 철저하게 검색했지만 일치, 병합, 대체를 기반으로하는 솔루션은 data.table 패키지가 작동하지 않는 것 같습니다.

감사합니다.

+0

안녕하세요, + 잘라 내기 + 붙여 넣기 예제입니다. 그러나 조금 더 질문을 단순화 해 주시면 답변을 더 빨리 게시 할 수 있습니다. –

+0

간단히 해보겠습니다 : 기본적으로 df1에는 값이 df2에있는 변수의 이름 인 일부 변수가 포함되어 있습니다. df1의 변수 값을 df2의 일치하는 변수 이름 아래에있는 실제 값으로 대체해야합니다. – user3108800

답변

0

여기서 문제는 데이터 형식이라고 생각합니다. 다음과 같이 "긴"테이블에 저장하는 것이 좋습니다 :

library(data.table) 
dt <- data.table(dummy_id = rep(dummy_id, 4), 
       type = rep(c("Animal", "Bacteria", "Mineral", "Plant"), each = 10), 
       name = c(Animal, Bacteria, Mineral, Plant), 
       drugA = c(AnimalDrugA, BacteriaDrugA, MineralDrugA, PlantDrugA), 
       drugB = c(AnimalDrugB, BacteriaDrugB, MineralDrugB, PlantDrugB)) 

그런 다음 필터링하고 다른 작업을 수행하는 것이 훨씬 쉽습니다. 예를 들어,

dt[name == "bronze"][order(dummy_id)] 

솔직하게 나는 당신이 결국 달성하고자하는 것을 잘 모르겠다.

관련 문제