簡體   English   中英

合並數據集,其中鍵位於R中一個數據集的列和另一數據集的行上

[英]Merging datasets where the key is on the column of one dataset and row of another in R

如何合並鍵在R中一個數據集的列和另一行的鍵處的數據集?

示例數據:

group = c("a", "b", "c", "c")
id1 = c(1, 0, 0, 0) 
id2 = c(0, 1, 0, 1)
id3 = c(0, 0, 1, 0) 
df1 = data.frame(group,id1, id2, id3) 
df1

id = c("id1", "id2", "id3") 
iv1 = c(2, 3, 3) 
iv2 = c(3, 2, 3) 
df2 = data.frame(id, iv1, iv2) 
df2

我喜歡按ID合並這兩個數據集。 我可以通過ifelse做到這一點:

df1$iv1 = ifelse(df1$id1 == 1, 2, 3)
df1$iv2 = ifelse(df1$id2 == 1, 2, 3)

結果:

  group id1 id2 id3 iv1 iv2
1     a   1   0   0   2   3
2     b   0   1   0   3   2
3     c   0   0   1   3   3
4     c   0   1   0   3   2

如果說,如果我要合並1000個變量,那么ifelse的方法將很乏味。 有沒有更有效的方法來合並這樣的數據集?

我們可以使用第一個列的順序與第二個列的順序匹配的事實。

df1[c("iv1", "iv2")] <- df2[max.col(df1[-1]),-1]
#   group id1 id2 id3 iv1 iv2
# 1     a   1   0   0   2   3
# 2     b   0   1   0   3   2
# 3     c   0   0   1   3   3
# 4     c   0   1   0   3   2

Pierre Lafortune已經給出了很好的答案。 我仍然會發布我的解決方案:

ids <- colnames(df1[, 2:4])
ids <- apply(df1[, 2:4], 1, function(x) return(ids[as.logical(x)]))

df1$id <- ids
new_df <- merge(df1, df2, by="id", all.x = TRUE, sort=FALSE)

> new_df
   id group id1 id2 id3 iv1 iv2
1 id1     a   1   0   0   2   3
2 id2     b   0   1   0   3   2
3 id2     c   0   1   0   3   2
4 id3     c   0   0   1   3   3

Pierre和Istrel的答案都很好。 對於此操作和更復雜的操作,您還可以使用Hadley Wickham流行的tidyr程序包:

install.packages('tidyr', repos='http://cran.rstudio.org')
library(tidyr)

g1 <- gather(df1, idx, id_val, -group)  # colnames are in 'idx'; 12 rows total
g1 <- g1[g1$id_val==1, ]                # drop rows with id_val == 0
g2 <- merge(g1, df2, by.x='idx', by.y='id')
g3 <- spread(g2, idx, id_val)           # pivot the 'idx' column back out
g3
#   group iv1 iv2 id1 id2 id3
# 1     a   2   3   1  NA  NA
# 2     b   3   2  NA   1  NA
# 3     c   3   2  NA   1  NA
# 4     c   3   3  NA  NA   1
g3[is.na(g3)] <- 0
g3
#   group iv1 iv2 id1 id2 id3
# 1     a   2   3   1   0   0
# 2     b   3   2   0   1   0
# 3     c   3   2   0   1   0
# 4     c   3   3   0   0   1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM