Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中从长格式转换为对称的正方形宽格式_R_Reshape - Fatal编程技术网

在R中从长格式转换为对称的正方形宽格式

在R中从长格式转换为对称的正方形宽格式,r,reshape,R,Reshape,我想转换这个数据帧 tmp <- data.frame(V1=c("A","A","B"),V2=c("B","C","C"),V3=c(0.2,0.4,0.1)) tmp V1 V2 V3 1 A B 0.2 2 A C 0.4 3 B C 0.1 我尝试了基于函数重塑、扩展或xtabs的不同方法,但无法获得正确的维度。谢谢你的帮助。也许你可以试试下面的代码 d <- sort(unique(unlist(tmp[1:2]))) m <- `dimname

我想转换这个数据帧

tmp <- data.frame(V1=c("A","A","B"),V2=c("B","C","C"),V3=c(0.2,0.4,0.1))
tmp
  V1 V2  V3
1  A  B 0.2
2  A  C 0.4
3  B  C 0.1

我尝试了基于函数
重塑
扩展
xtabs
的不同方法,但无法获得正确的维度。谢谢你的帮助。

也许你可以试试下面的代码

d <- sort(unique(unlist(tmp[1:2])))
m <- `dimnames<-`(matrix(0,length(d),length(d)),list(d,d))
m[as.matrix(tmp[1:2])] <- tmp$V3
res <- t(m) + m

也许你可以试试下面的代码

d <- sort(unique(unlist(tmp[1:2])))
m <- `dimnames<-`(matrix(0,length(d),length(d)),list(d,d))
m[as.matrix(tmp[1:2])] <- tmp$V3
res <- t(m) + m

您还可以使用
结构
以这种方式创建自己的
dist
对象:

tmp_lab <- unique(c(as.character(tmp$V1), as.character(tmp$V2)))

structure(tmp$V3,
          Size = length(tmp_lab),
          Labels = tmp_lab,
          Diag = TRUE,
          Upper = FALSE,
          method = "user",
          class = "dist")

您还可以使用
结构
以这种方式创建自己的
dist
对象:

tmp_lab <- unique(c(as.character(tmp$V1), as.character(tmp$V2)))

structure(tmp$V3,
          Size = length(tmp_lab),
          Labels = tmp_lab,
          Diag = TRUE,
          Upper = FALSE,
          method = "user",
          class = "dist")

将列“V1”、“V2”转换为
因子后,这里有一个
xtabs
选项,其中
级别指定为相同

tmp[1:2] <- lapply(tmp[1:2], factor, levels = c('A', 'B', 'C'))
as.dist(xtabs(V3 ~ V2 + V1, tmp), diag = TRUE)
#    A   B   C
#A 0.0        
#B 0.2 0.0    
#C 0.4 0.1 0.0

tmp[1:2]在将列“V1”、“V2”转换为
因子后,这里有一个选项,其中
xtabs
的级别指定为相同

tmp[1:2] <- lapply(tmp[1:2], factor, levels = c('A', 'B', 'C'))
as.dist(xtabs(V3 ~ V2 + V1, tmp), diag = TRUE)
#    A   B   C
#A 0.0        
#B 0.2 0.0    
#C 0.4 0.1 0.0

tmp[1:2]智能构建
dist
对象+1构造
dist
对象时要明智+1.