[英]Matrix stacking with column name in R
I found many threads related to matrix stacking with column name but there is no information which help in this problem. 我发现许多与具有列名的矩阵堆栈有关的线程,但是没有任何信息可以帮助解决此问题。 I have a matrix like this
我有一个这样的矩阵
Lcover County 8 9 53009 868.935 1171.0050 53055 NA 414.9733 53057 NA 276.5450 53073 706.700 NA
and I am trying to create a dataframe like this 我正在尝试创建这样的数据框
County Lcover Value
53009 8 868.935
53009 9 1171.0050
53055 9 414.9733
53057 9 276.5450
53073 8 706.700
Would anyone suggest me, how can I do this? 有人会建议我,我该怎么做?
Thanks in advance. 提前致谢。
Deven 德文
As Andrie noted, melt()
function makes this trivially easy: 正如Andrie指出的那样,
melt()
函数使此操作变得简单:
x <- read.table(text = "County 8 9
53009 868.935 1171.0050
53055 NA 414.9733
53057 NA 276.5450
53073 706.700 NA ", header = TRUE)
require(reshape2)
melt(x, id.vars = "County", na.rm=TRUE)
County variable value
1 53009 X8 868.9350
4 53073 X8 706.7000
5 53009 X9 1171.0050
6 53055 X9 414.9733
7 53057 X9 276.5450
The "X" appears in front of your columns because R tries to make valid column names with the make.names()
function. “ X”出现在您的列的前面,因为R试图使用
make.names()
函数创建有效的列名。 You can disable that functionality with check.names = FALSE
when reading in / creating your table. 读入/创建表时,可以使用
check.names = FALSE
禁用该功能。 Or just drop the X from the resulting column with gsub("X","", variable)
.If you want to retain the NA values in the melted data.frame, change na.rm = FALSE
in the melt()
function. 或者只是使用
gsub("X","", variable)
从结果列中删除X。如果要在熔化的data.frame中保留NA值,请在melt()
函数中更改na.rm = FALSE
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.