我在csv文件中有一个x,y和z矩阵,其中x和y是z值的物理位置。第一列是x位置,第一行是y位置。
0 1 2 3 4 5 6
0 z values
1
2
3
4
我想建立一个三列的矩阵和/或数据框,例如:
X Y Z
0 0 6.7
0 1 9.0
等等。
目的是创建这些数据的浮雕图或xyz图。
有关清理此事的想法吗?
raw <- as.data.frame(read.csv(choose.files(), header = FALSE))
raw <- raw[2:15, 2:29]
rownames(raw) <- 0:13
colnames(raw) <- 0:27
g <- transform(expand.grid(x=as.numeric(rownames(raw)),
y=as.numeric(colnames(raw))),
z=unlist(raw))
第二行是将raw
声明为z
值。
关于概括第二,第三和第四行的任何想法?
答案 0 :(得分:2)
试试这个:
transform(expand.grid(x=as.numeric(rownames(df)),
y=as.numeric(colnames(df))),
z=unlist(df))
测试数据(来自@Roland)
set.seed(42)
m <- matrix(rnorm(25),ncol=5)
df <- as.data.frame(m)
rownames(df) <- colnames(df) <- 0:4
# x y z
# 01 0 0 1.37095845
# 02 1 0 -0.56469817
# 03 2 0 0.36312841
# 04 3 0 0.63286260
# 05 4 0 0.40426832
# 11 0 1 -0.10612452
# 12 1 1 1.51152200
# 13 2 1 -0.09465904
# 14 3 1 2.01842371
# 15 4 1 -0.06271410
# 21 0 2 1.30486965
# 22 1 2 2.28664539
# 23 2 2 -1.38886070
# 24 3 2 -0.27878877
# 25 4 2 -0.13332134
# 31 0 3 0.63595040
# 32 1 3 -0.28425292
# 33 2 3 -2.65645542
# 34 3 3 -2.44046693
# 35 4 3 1.32011335
# 41 0 4 -0.30663859
# 42 1 4 -1.78130843
# 43 2 4 -0.17191736
# 44 3 4 1.21467470
# 45 4 4 1.89519346