简体   繁体   中英

Re-arrange a table in R

I'm reading a .dat file in R which has 10,800 rows and 6 columns (I'll leave you the link to the file if you want to take a look )

In order to read it I use this:

library(dplyr)
library(readr)

tryon <- read.table("F:/1981_01_NAM.dat", header=FALSE)

Once I have that table I want to re-arrange it making an array or matrix that has 360 rows and 180 columns. For example I have this:

   [1]   [2]  [3]

[1]1     2     3
[2]4    5      6
[3]7    8      9

And I want this:

   [1]   [2]  [3]  [4]   [5]  [6]

[1]1     2     3   4   5   6
[3]7    8      9   ...

So by following some examples I used:

lon = 360
lat = 180

output2 <- matrix(unlist(tryon), nrow = lon, ncol= lat, byrow = TRUE)

But it does not do what I want, if you use the data I linked above, after the re-arrange the value at the position [1,35] should be -0.00367983, but I get a 0.

Any ideas? Thank you.

If you just try to use unlist(tyron) , you'll see that it doesn't do anything because matrices aren't lists. So you'll have to turn it into a list, and then unlist it which effectively turns it into a single vector. Then you can use the matrix function to turn it back into a matrix.

is.list(mat)
FALSE

try:

output2 <- matrix(unlist(as.list(tyron)), nrow = lon, ncol = lat, byrow = TRUE)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM