将两个数据帧中的数据关联为一个,同时保留原始数据的信息

时间:2019-04-29 15:02:02

标签: r dataframe correlation

我必须将信息从两个数据帧转换为一个矩阵,该矩阵是为进一步分析而特别设计的。我将从介绍一个正在使用的数据类型的玩具示例开始。

Game1 <- structure(list(Score1 = c(5, 9), Score2 = c(4.8, 12.8), Score3 = c(7.22, 
2.3), Class = structure(2:1, .Label = c("Dwarf", "Paladin"), class = "factor"), 
    Race = structure(1:2, .Label = c("Dwarf,", "Elf"), class = "factor")), row.names = c("Stan", 
"Kyle"), class = "data.frame")

Game2 <- structure(list(Score1 = c(3, 8.1), Score2 = c(6.3, 6.6), Score3 = c(1.2, 
10.3), Class = structure(2:1, .Label = c("Rouge", "Wizard"), class = "factor"), 
    Race = structure(2:1, .Label = c("Gnome", "Human,"), class = "factor")), row.names = c("Cartman", 
"Kenny"), class = "data.frame")

我想对不同球员的得分进行关联,理想的情况是平均皮尔森关联。我想保留原始两个数据帧中的某些残差特征,如下所示。

我希望从中得到的输出是:

             Correlation Game1_Class Game1_Race Game2_Class Game2_Race

Stan:Cartman   -0.815    Paladin     Dwarf      Wizard      Human
Kyle:Cartman    0.942    Fighter     Elf        Wizard      Human
Stan:Kenny      0.947    Wizard      Human      Ranger      Gnome
Kyle:Kenny     -0.998    Rouge       Gnome      Ranger      Gnome

我使用通用系数相关性来计算相关性,我更喜欢使用皮尔逊或斯皮尔曼。

每个数据帧(在我的真实数据中)的行数差异很大。

1 个答案:

答案 0 :(得分:2)

您可以定义一个创建此表的自定义函数

val num = Array("one", "two", "three")
val stringToInt = num.zipWithIndex.toMap.mapValues(_ + 1)
// Map("one" -> 1, "two" -> 2, "three" -> 3)

val two: Int = stringToInt("two")
相关问题