2012-11-08 4 views
10

Ho due frame di dati grandi, uno (df1) ha questa strutturacorrispondenza più colonne su diversi frame di dati e ottenere altri colonna come risultato

chr init 
1 12 25289552 
2 3 180418785 
3 3 180434779 

L'altro (df2) ha questo

V1 V2  V3 
10 1  69094 medium 
11 1  69094 medium 
12 12 25289552 high 
13 1  69095 medium 
14 3 180418785 medium 
15 3 180434779 low 

Quello che sto cercando di fare è aggiungere la colonna V3 di df2 a df1, per ottenere le informazioni della mutazione

chr init Mut 
1 12 25289552 high 
2 3 180418785 medium 
3 3 180434779 low 

Sto provando a caricare sia in R che a fare un ciclo for usando la corrispondenza ma non funziona. Conosci qualche modo speciale per farlo? Sono aperto anche a che fare con awk o qualcosa di simile

risposta

12

Usa merge

df1 <- read.table(text=' chr init 
1 12 25289552 
2 3 180418785 
3 3 180434779', header=TRUE) 


df2 <- read.table(text=' V1 V2  V3 
10 1  69094 medium 
11 1  69094 medium 
12 12 25289552 high 
13 1  69095 medium 
14 3 180418785 medium 
15 3 180434779 low', header=TRUE) 


merge(df1, df2, by.x='init', by.y='V2') # this works! 
     init chr V1  V3 
1 25289552 12 12 high 
2 180418785 3 3 medium 
3 180434779 3 3 low 

Per ottenere l'output desiderato il modo di vederlo

output <- merge(df1, df2, by.x='init', by.y='V2')[, c(2,1,4)] 
colnames(output)[3] <- 'Mut' 
output 
    chr  init Mut 
1 12 25289552 high 
2 3 180418785 medium 
3 3 180434779 low 
+0

Sì, questo quello che voglio, il punto è che devo prendere in considerazione la anche cromosoma, quindi forse qualcosa del genere si fonde (df1, df2, by.x = c ('chr', 'init'), by.y = c ('V1', V2 ') [, c (2,1, 4)] – user976991

+0

Esattamente, basta aggiungere 'chr' e' V1' agli argomenti per tenerli in considerazione: D Considerare upv ota le risposte utili e accetta una di queste se la trovi utile: D –

0

Vuol

df3 <- merge(df1, df2, by.x = "init", by.y = "V2") 
df3 <- df3[-3] 
colnames(df3)[3] <- "Mut" 

darvi ciò che si vuole?

2
df1 <- read.table(textConnection(" chr init 
1 12 25289552 
2 3 180418785 
3 3 180434779"), header=T) 

df2 <- read.table(textConnection(" V1 V2  V3 
10 1  69094 medium 
11 1  69094 medium 
12 12 25289552 high 
13 1  69095 medium 
14 3 180418785 medium 
15 3 180434779 low"), header=T) 

# You have to select the values of df2$V3 such as their corresponding V2 
# are equal to the values of df1$init 
df1$Mut <- df2$V3[ df2$V2 %in% df1$init] 

df1 
    chr  init Mut 
1 12 25289552 high 
2 3 180418785 medium 
3 3 180434779 low 
+0

Nota che questo non funzionerà se ci sono valori chiave in 'df1' che sono assenti da' df2'. Si otterrebbe un errore come "la sostituzione ha 3 righe, i dati ne hanno 4". Vedi http://stackoverflow.com/questions/1299871/how-to-join-merge-data-frames-inner-outer-left-right/38130460#38130460 per un'implementazione del join sinistro usando 'match()'. – bgoldst