使用 R 重塑数据

Reshape Data using R

我是 R 的新手,我有如下数据

NAME
----
Balachandra
Sunita
Kali
Jagmeet

我想把它变成

NAME1       NAME2
-----------------------
Balachandra Balachandra
Balachandra Sunita
Balachandra Kali
Balachandra Jagmeet    
Sunita      Balachandra
Sunita      Sunita
Sunita      Kali
Sunita      Jagmeet    
Kali        Balachandra
Kali        Sunita
Kali        Kali
Kali        Jagmeet    
Jagmeet     Balachandra
Jagmeet     Sunita
Jagmeet     Kali
Jagmeet     Jagmeet    

拥有所有可能的名字组合

知道怎么做吗?

我们可以使用expand.grid

expand.grid(NAME1=df1$NAME, NAME = df1$NAME)[2:1]
#      NAME         NAME1
#1  Balachandra Balachandra
#2  Balachandra      Sunita
#3  Balachandra        Kali
#4  Balachandra     Jagmeet
#5       Sunita Balachandra
#6       Sunita      Sunita
#7       Sunita        Kali
#8       Sunita     Jagmeet
#9         Kali Balachandra
#10        Kali      Sunita
#11        Kali        Kali
#12        Kali     Jagmeet
#13     Jagmeet Balachandra
#14     Jagmeet      Sunita
#15     Jagmeet        Kali
#16     Jagmeet     Jagmeet

或使用 data.table

中的 CJ
library(data.table)
setDT(df1, key = "Name")[CJ(Name, Name)]

数据

df1 <- data.frame(NAME = c("Balachandra", "Sunita", "Kali", 
               "Jagmeet"), stringsAsFactors=FALSE)