R Reshape data by combining common value of two variables
问题 I want to reshape a data frame by combining two variables. For example: Here is a new data: dat = data.frame( var1 = c("a", "a", "a", "Emily", "b", "Bob", "c"), var2 = c("Jhon", "Emily", "Julie", "Angela", "Bob", "Paul", "Paul"), stringsAsFactors = F ) Excepted output: # var1 var2 var3 var4 var5 # 1 a Jhon Emily Julie Angela # 2 b Bob Paul c <NA> 回答1: Using base R you can do: relation=function(dat){ .relation=function(x){ k = unique(sort(c(dat[dat[, 1] %in% x, 2], x, dat[dat[, 2] %in% x, 1]))