組合

2015-04-25 29 views
3

我點名,我想結合其載體如下:組合

v1 <- c(0,1,2,3) 
v2 <- c(0,1,2,3) 
v3 <- c(0,1,2,3) 
names(v1) <- c("This","is","an","example") 
names(v2) <- c("This","great","value","random") 
names(v3) <- c("This","This","and","This") 

爲預期的結果V1和V2:

This is an example great value random 
0 1 2 3  1  2  3 

和V1和V3:

This is an example This and This 
0 1 2 3  1 2 3 

正如您所看到的,如果名稱不同,矢量就會綁定在一起。如果結果向量中有多個名稱出現,如果相應的值相同,則保留一次,但如果值與每次出現的值不同,則保留多次。 我不知道我是否明確了要實現的目標。

是否可以實現這樣的目標? 謝謝

回答

4

我會做一個輔助功能,如:

Combiner <- function(vec1, vec2, vecOut = TRUE) { 
    temp <- unique(rbind(data.frame(as.table(vec1)), 
         data.frame(as.table(vec2)))) 
    if (isTRUE(vecOut)) setNames(temp$Freq, temp$Var1) 
    else temp 
} 

的一點是要比較這兩個名稱和值,我發現它簡單的方法就是將它放入的形式data.frame。然後

用法是:

Combiner(v1, v2) 
# This  is  an example great value random 
#  0  1  2  3  1  2  3 
Combiner(v1, v3) 
# This  is  an example This  and This 
#  0  1  2  3  1  2  3 

對於任何數量的載體,你可以修改的功能是這樣的:

Combiner <- function(..., vecOut = TRUE) { 
    dots <- list(...) 
    if (any(is.null(sapply(dots, names)))) stop("All vectors must be named") 
    temp <- unique(do.call(rbind, lapply(dots, function(x) { 
    data.frame(Name = names(x), Value = unname(x), stringsAsFactors = FALSE) 
    }))) 
    if (isTRUE(vecOut)) setNames(temp$Value, temp$Name) 
    else temp 
} 

雖然第一個版本將只與工作數字命名向量(因爲它使用as.table),第二個版本也應該使用命名字符向量。

+0

好吧,它適用於示例數據 - 迄今爲止非常好。在我的真實數據,這是生成的所有相同,但類型字符而不是數字,我得到以下錯誤:'獨特的錯誤(rbind(data.frame(as.table(vec1)),data.frame(as。 table(vec2)))): 在選擇函數'unique'的方法時評估參數'x'時出錯:as.table.default(vec2)中的錯誤:無法強制到表' – MineSweeper

+1

@MineSweeper,不確定。我剛剛在帖子末尾更新了「合併器」功能,以便不使用「表格」。你可以試試這個版本嗎? – A5C1D2H2I1M1N2O1R2T1

+0

作品完美的第二個版本(我不得不刪除'isTRUE')謝謝;) – MineSweeper