My data format in csv is the following. I would like to create a matrix for heatmap using this file. R gglot i am going to use.
A B C 1 apple 3 2 book 5 4 bag 1 9 desk 4 10 apple 8 11 book 66 14 desk 2
I would like to create a matrix for heatmap using that above file.
1 2 4 9 10 11 14
apple 3 0 0 0 8 0 0
book 0 5 0 0 0 66 0
bag 0 0 1 0 0 0 0
desk 0 0 0 4 0 0 2
i have another column in initial file for ordering.
A B C D 1 apple 3 4 2 book 5 1 4 bag 1 2 9 desk 4 3 10 apple 8 4 11 book 66 1 14 desk 2 3
how can i order my matrix due to this D ordering column? or i would like to order by sum of 1-14 column.
You can use xtabs
.
d <- read.delim(textConnection("
A B C
1 apple 3
2 book 5
4 bag 1
9 desk 4
10 apple 8
11 book 66
14 desk 2
"), sep=" ")
xtabs(C ~ B + A, d)
A
B 1 2 4 9 10 11 14
0 0 0 0 0 0 0
apple 3 0 0 0 8 0 0
bag 0 0 1 0 0 0 0
book 0 5 0 0 0 66 0
desk 0 0 0 4 0 0 2
You can do this with read.table
. You can get the help for choosing the correct parameters by typing ?read.table
into your R-GUI.
Using the read.delim part from Vincent above and a reshape approach. Not as elegant...
d <- read.delim(textConnection("
A B C
1 apple 3
2 book 5
4 bag 1
9 desk 4
10 apple 8
11 book 66
14 desk 2
"), sep=" ")
Var1 <- rep(d[,1], d[,3])
Var2 <- rep(d[,2], d[,3])
d <- data.frame(Var1=Var1, Var2=Var2)
d <- cast(melt(d), Var2~value)
> d
Var2 1 2 4 9 10 11 14
1 apple 3 0 0 0 8 0 0
2 bag 0 0 1 0 0 0 0
3 book 0 5 0 0 0 66 0
4 desk 0 0 0 4 0 0 2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.