假设我有这种输入数据,一个文件是一个data.frame文件,其中的数据格式很长,只有Species_A和Species_B之间的唯一性比较如下:
Species_A Species_B values
A B 58
A C 64
A D 78
A E 32
B C 10
B D 12
B E 54
C D 99
C E 84
D E 42
我想知道如何轻松地将输入文件转换为方矩阵
A B C D E
A 100 58 64 78 32
B 58 100 10 12 54
C 64 10 100 99 84
D 78 12 99 100 42
E 32 54 84 42 100
使用tidyverse函数的解决方案 :
library(tidyverse)
cor_data <- tribble(
~Species_A, ~Species_B, ~values,
"A","B",58,
"A","C",64,
"A","D",78,
"A","E",32,
"B","C",10,
"B","D",12,
"B","E",54,
"C","D",99,
"C","E",84,
"D","E",42)
expand.grid(unique(cor_data[["Species_A"]]), unique(cor_data[["Species_A"]])) %>%
left_join(cor_data, by =c("Var1" = "Species_A", "Var2" = "Species_B")) %>%
left_join(cor_data, by =c("Var1" = "Species_B", "Var2" = "Species_A")) %>%
transmute(Species_A = Var1, Species_B = Var2, values = coalesce(values.x, values.y)) %>%
spread(Species_B, values)
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。