防止 reshape2 将列标题转换为数字
Prevent reshape2 from converting column headings to numbers
我正在尝试使用 Lars Relund Nielsen webpage 上显示的 GoogleMaps 模型从美国邮政编码位置的实际距离矩阵创建查找 table。美国东北部的邮政编码以“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
但是当我将矩阵重塑为查找 table 时,它会将 row/col 名称转换为数字,从邮政编码中删除前导零。
#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 将邮政编码转换为数字有什么想法吗?
在您的 melt
函数中包含 as.is=TRUE:
dat<-(melt(mdat, as.is=TRUE))
colnames(dat)<-c("from","to","km")
这将在熔化过程中将列名称保留为字符串。
我正在尝试使用 Lars Relund Nielsen webpage 上显示的 GoogleMaps 模型从美国邮政编码位置的实际距离矩阵创建查找 table。美国东北部的邮政编码以“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
但是当我将矩阵重塑为查找 table 时,它会将 row/col 名称转换为数字,从邮政编码中删除前导零。
#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 将邮政编码转换为数字有什么想法吗?
在您的 melt
函数中包含 as.is=TRUE:
dat<-(melt(mdat, as.is=TRUE))
colnames(dat)<-c("from","to","km")
这将在熔化过程中将列名称保留为字符串。