0

I have some work in R, Suppose i have following column data

Lat Lon Var1 Var2 Var3

with the huge number of patterns, since the data are vector i want to change that data into grid matrix. for example

    Lon Lon Lon
Lat Var1 Var1 Var1
Lat Var1 Var1 Var1
Lat Var1 Var1 Var1

what is the most effective command in R, thanks

totti saga
  • 3
  • 1
  • 4
  • 1
    Please see [how to make a great reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) in the SO R FAQ. – hrbrmstr Dec 05 '14 at 01:12

2 Answers2

1

As indicated in the comments, it's best to post with an example:

dat <- data.frame(Lat=rep(1:3, each=3), Lon=rep(1:3, 3), Var1=1:9, Var2=11:19, Var3=21:29)
dat
#   Lat Lon Var1 Var2 Var3
# 1   1   1    1   11   21
# 2   1   2    2   12   22
# 3   1   3    3   13   23
# 4   2   1    4   14   24
# 5   2   2    5   15   25
# 6   2   3    6   16   26
# 7   3   1    7   17   27
# 8   3   2    8   18   28
# 9   3   3    9   19   29

It sounds like you're trying to move from long format to wide format; you can do this with the reshape function:

reshape(dat[,c("Lon", "Lat", "Var1")], timevar="Lon", idvar="Lat", direction="wide")
#   Lat Var1.1 Var1.2 Var1.3
# 1   1      1      2      3
# 4   2      4      5      6
# 7   3      7      8      9
josliber
  • 43,891
  • 12
  • 98
  • 133
  • thanks before for the sample. in cased if i wanna change into a matrix with lat (vertical) lon (horizontal) and var1 (values) – totti saga Dec 05 '14 at 03:39
1

You could also use acast from reshape2

library(reshape2)
acast(df, Lat~Lon, value.var='Var1')

If you want to change the horizontal/vertical positions

m1 <- acast(df, Lon~Lat, value.var='Var1')
dimnames(m1) <- list(rep('Lon', 3), rep('Lat',3))

Using @josiber's example, m1 would be

m1
#    Lat Lat Lat
#Lon   1   4   7
#Lon   2   5   8
#Lon   3   6   9

Other option would be to use xtabs from base R

xtabs(Var1~Lon+Lat, df)
#   Lat
#Lon 1 2 3
#  1 1 4 7
#  2 2 5 8
#  3 3 6 9

Suppose if you need all the Var's

acast(melt(df, id.var=c('Lat', 'Lon')), Lon~Lat+variable)
akrun
  • 874,273
  • 37
  • 540
  • 662