0
votes

Trying to re-organise a data set (sdevDFC) into a matrix with my latitude (Lat) as row names and longitude (Lon) as column names, then filling in the matrix with values respective to the coordinates.

stand_dev_m <- matrix(data=sdevDFC$SDev, nrow=length(sdevDFC$Lat), ncol=length(sdevDFC$Lon), byrow=TRUE, dimnames = list(sdevDFC$Lat, sdevDFC$Lon))

The column and row names appear as they should, but my data fills in so that all values in their respective columns are identical as shown in the image (which should not be the case as none of my values ever repeat).

I've filled it with byrow = FALSE to see if it also occurred then (it does), and I've also used colnames and rownames instead of dimnames (changes nothing).

Would appreciate any insight into what I may be doing wrong here--also new to this platform so I apologise if I've missed a guideline or another question that's similar

1
This is because your dataframe has n rows (length(sdevDFC$Lat) etc), and you are therefore only giving it n data values (from the same dataframe), which therefore repeat to fill the n x n grid.Andrew Gustar
Hi @STK if my answer helped solve your issue please consider accepting it as an answer by clicking on the check mark to the left. This lets the community know that it worked.CPak

1 Answers

0
votes

Example data:

df <- data.frame(LON=1:5,
                 LAT=11:15,
                 VAL=letters[1:5],
                 stringsAsFactors=F)

You could try the following:

rn <- df$LON            # Save what-will-be-rownames
df1 <- df %>% 
         spread(LAT,VAL,fill=NA) %>%
         select(-LON) %>%
         setNames(., df$LAT)
rownames(df1) <- rn

Output

    11   12   13   14   15
1    a <NA> <NA> <NA> <NA>
2 <NA>    b <NA> <NA> <NA>
3 <NA> <NA>    c <NA> <NA>
4 <NA> <NA> <NA>    d <NA>
5 <NA> <NA> <NA> <NA>    e