【问题标题】:convert from long to symmetrical square wide format in R在R中从长格式转换为对称方形宽格式
【发布时间】:2020-04-28 15:04:55
【问题描述】:

我想转换这个数据框

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

变成这样的方阵(最终应该是dist 对象

  A B C
A 0
B 0.2 0
C 0.4 0.1 0

我尝试了基于函数 reshapespreadxtabs 的不同方法,但我无法获得正确的维度。感谢您的帮助。

【问题讨论】:

    标签: r reshape


    【解决方案1】:

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

    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
    

    这样

    > res
        A   B   C
    A 0.0 0.2 0.4
    B 0.2 0.0 0.1
    C 0.4 0.1 0.0
    

    【讨论】:

      【解决方案2】:

      您也可以使用structure 以这种方式创建自己的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")
      

      输出

          A   B   C
      A 0.0        
      B 0.2 0.0    
      C 0.4 0.1 0.0
      

      【讨论】:

      • 智能构造dist对象! +1
      【解决方案3】:

      在将列 'V1' 、 'V2' 转换为 factor 并指定 levels 后,这是一个带有 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-25
        • 2013-10-22
        • 1970-01-01
        • 1970-01-01
        • 2018-01-31
        • 2015-07-18
        相关资源
        最近更新 更多