2017-06-16 4 views
0

Ich hoffe, jemand kann helfen. Ich habe eine Menge von Ortholog-Mapping in R zu tun, was sich als unglaublich zeitaufwendig erweist. Ich habe unten eine Beispielstruktur veröffentlicht. Offensichtliche Antworten wie das Iterieren von Zeile für Zeile (für i in 1: nw (df)) und String-Splitting oder die Verwendung von Sapply wurden ausprobiert und sind unglaublich langsam. Ich hoffe daher auf eine vektorisierte Option.Optimierung der Anpassung in R

stringsasFactors = F 

# example accession mapping 
map <- data.frame(source = c("1", "2 4", "3", "4 6 8", "9"), 
        target = c("a b", "c", "d e f", "g", "h i")) 

# example protein list 
df <- data.frame(sourceIDs = c("1 2", "3", "4", "5", "8 9")) 

# now, map df$sourceIDs to map$target 


# expected output 
> matches 
[1] "a b c" "d e f" "g"  ""  "g h i" 

Ich weiß jede Hilfe zu schätzen!

Antwort

1

In den meisten Fällen besteht der beste Ansatz für diese Art von Problem darin, data.frames mit einer Beobachtung pro Zeile zu erstellen.

map_split <- lapply(map, strsplit, split = ' ') 
long_mappings <- mapply(expand.grid, map2$source, map2$target, SIMPLIFY = FALSE) 
all_map <- do.call(rbind, long_mappings) 
names(all_map) <- c('source', 'target') 

sieht nun all_map wie folgt aus:

source target 
1  1  a 
2  1  b 
3  2  c 
4  4  c 
5  3  d 
6  3  e 
7  3  f 
8  4  g 
9  6  g 
10  8  g 
11  9  h 
12  9  i 

tun das gleiche für df ...

sourceIDs_split <- strsplit(df$sourceIDs, ' ') 
df_long <- data.frame(
    index = rep(seq_along(sourceIDs_split), lengths(sourceIDs_split)), 
    source = unlist(sourceIDs_split) 
) 

uns Geben Sie diese für df_long:

index source 
1  1  1 
2  1  2 
3  2  3 
4  3  4 
5  4  5 
6  5  8 
7  5  9 

Jetzt müssen sie nur zusammengeführt und zusammengelegt werden.

matches <- merge(df_long, all_map, by = 'source', all.x = TRUE) 
tapply(
    matches$target, 
    matches$index, 
    function(x) { 
    paste0(sort(x), collapse = ' ') 
    } 
) 

#  1  2  3  4  5 
# "a b c" "d e f" "c g"  "" "g h i" 
+0

'lapply (map, strsplit, split = '')' gibt mir einen Fehler. Geht das für dich? – CPak

+0

Dies ist eine großartige Lösung. Vielen Dank. – user8173495

+1

@ChiPak Ich nahm vom ursprünglichen Beispiel an, dass 'options (stringsAsFactors = FALSE) '. Meine Lösung wird nicht funktionieren, wenn die Spalten von 'map' Faktoren sind. –