2017-10-15 38 views
0

#數據1如何使用「merge,by = Column.name」函數合併具有不同名稱的列?

SampleID <- c("A-01","B-01","C-01") 
Value <- c(1,2,3) 
data1 <- data.frame(SampleID, Value) 

#數據2

SampleID <- c("A","B","C") 
Value1 <- c(3,4,5) 
data2 <- data.frame(SampleID,Value1) 

#輸出:我想是使用以下: merge(data1, data2, by=c("SampleID"), all = TRUE)

SampleID Value Value1 
A-01  1  3 
B-01  2  4 
C-01  3  5 
+2

使用參數'by.x'和'by.y'。 –

+1

所以你想合併行'A-01'和行'A'等?如果是這樣,你必須首先使這些值相等,用'gsub'創建一個新列。 –

回答

2

刪除data1多餘的欄,可以首先從數據1分裂SampleID,然後拼接它。

SampleID <- c("A-01","B-01","C-01") 
Sample <- substr(SampleID,1,1) 
Num <- substr(SampleID,3,5) 
Value <- c(1,2,3) 
data1 <- data.frame(Sample ,Num, Value) 

SampleID <- c("A","B","C") 
Value1 <- c(3,4,5) 
data2 <- data.frame(SampleID, Value1) 

merged <- merge(data1, data2, by.x = "Sample", by.y = "SampleID", all = T) 
merged$SampleID <- paste(merged$Sample,merged$Num, sep = "-") 
merged <- merged[,c(5,3,4)] 

    SampleID Value Value1 
1  A-01  1  3 
2  B-01  2  4 
3  C-01  3  5 
1

可以使用sqldf庫做到這一點:

library(sqldf); 
sqldf("SELECT data1.SampledId, data1.Vlaue, data2.Value2 FROM data1 JOIN data2 on data1.SampleID like data1.SampleID + '-%'") 

或者使用data.table喜歡以下內容:

library(data.table) 
dt1 <- data.table(data1) 
dt2 <- data.table(data2) 
dt1[dt2, on = .(grepl(CustomerId, CustomerId)), all = TRUE] 
1

我相信下面做你所需要的。

data1$NewID <- gsub("[^[:alpha:]]", "", data1$SampleID) 
result <- merge(data1, data2, by.x = "NewID", by.y = "SampleID", all = TRUE) 
result <- result[-1] 
result 
# SampleID Value Value1 
#1  A-01  1  3 
#2  B-01  2  4 
#3  C-01  3  5 

可以再用

data1 <- data1[-3] 
1

要添加到收藏,這裏是一個dplyr解決方案,讀取更容易一點:

options(stringsAsFactors = F) 
SampleID <-c("A-01","B-01","C-01") 
Value <- c(1,2,3) 
data1 <- data.frame(SampleID, Value) 

SampleID <- c("A","B","C") 
Value1 <- c(3,4,5) 
data2 <- data.frame(SampleID,Value1) 

data1 %>% 
    mutate(new_id = gsub("[^[:alpha:]]", "", SampleID)) %>% 
    left_join(., data2, by = c("new_id" = "SampleID")) %>% 
    select(-new_id) 

    SampleID Value Value1 
1  A-01  1  3 
2  B-01  2  4 
3  C-01  3  5 
相關問題