【问题标题】:Prevent reshape2 from converting column headings to numbers防止 reshape2 将列标题转换为数字
【发布时间】:2016-05-02 21:20:32
【问题描述】:

我正在尝试使用 Lars Relund Nielsen 的webpage 上显示的 GoogleMaps 模型从美国邮政编码位置的实际距离矩阵创建查找表。美国东北部的邮政编码以“0”开头,因此当 reshape2 将矩阵从宽转换为长时,如他的页面所述。

5 个邮政编码之间距离 (km) 的示例矩阵:

    mdat <- matrix(c(0.000, 113.288, 145.986, 126.271, 368.354
             ,103.988, 0.000, 69.637, 49.922, 294.386
             ,144.851, 69.285, 0.000, 25.547, 244.024
             ,124.531, 48.965, 25.245, 0.000, 258.729
             ,368.346, 295.159, 243.478, 258.598, 0.000)
           , nrow = 5
           , ncol = 5
           , byrow = TRUE,
           dimnames = list(c("01014", "01747", "02144", "02453", "04040"),
                           c("01014", "01747", "02144", "02453", "04040")))
Looks like this (all well and good);

#       01014   01747   02144   02453   04040
#01014   0.000 113.288 145.986 126.271 368.354
#01747 103.988   0.000  69.637  49.922 294.386
#02144 144.851  69.285   0.000  25.547 244.024
#02453 124.531  48.965  25.245   0.000 258.729
#04040 368.346 295.159 243.478 258.598   0.000

但是当我将矩阵重塑为查找表时,它会将行/列名称转换为从邮政编码中删除前导零的数字。

#reshape into a table of distances
library(reshape2)
dat<-(melt(mdat))
dat
colnames(dat)<-c("from","to","km")
head(dat)

  from   to      km
1 1014 1014   0.000
2 1747 1014 103.988
3 2144 1014 144.851
4 2453 1014 124.531
5 4040 1014 368.346
6 1014 1747 113.288

我希望得到;

from   to      km
1 01014 01014   0.000
2 01747 01014 103.988
3 02144 01014 144.851
4 02453 01014 124.531
5 04040 01014 368.346
6 01014 01747 113.288

关于如何防止 reshape2 将邮政编码转换为数字有什么想法吗?

【问题讨论】:

    标签: r matrix reshape2


    【解决方案1】:

    在您的 melt 函数中包含 as.is=TRUE:

    dat<-(melt(mdat, as.is=TRUE))
    colnames(dat)<-c("from","to","km")
    

    这将在熔化过程中将列名保留为字符串。

    【讨论】:

    • @Imo - 当我在提供的示例中运行您的建议时,这似乎不起作用,“0”仍然被丢弃在“dat”数据集中..想法? - 也许还有另一种方法,不使用 reshape2 - 我愿意提供建议吗?
    • @RobertWhite 你确定吗?我在两台不同的机器上运行了相同的代码(只是复制和粘贴你的 mdat 矩阵代码,然后是我的 dat 熔化代码),并在两台机器上都得到前导零。
    • @Imo - 有趣的是,当我在 Rstudio 中运行它时,它会删除前导的“0”,但在 R 中运行时 - 它有效!...我没有意识到,我可能应该指出Rstudio 在我的问题中,有区别吗?
    • @RobertWhite 这真的很奇怪。我在两台机器上通过 rstudio 运行代码,既直接复制到控制台,也复制到脚本并从那里运行。应该没关系,不过你有最新版的rstudio和reshape2吗?
    • @Imo,你解开了谜团——reshape2 过时了!感谢您的帮助!
    猜你喜欢
    • 2023-01-17
    • 2023-02-09
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    相关资源
    最近更新 更多