Moo
Moo

Reputation: 31

Converting non-numeric matrix into numeric

I have an imported table with longitudes and latitudes and want to create a spatial grid from them. The coordinates are in this format:

[1] 6.955 6.937 6.956 6.923

So looks numeric for me. But trying to create the grid this Error occurs:

Error in .local(obj, ...) :
cannot derive coordinates from non-numeric matrix

When I try to change the format using as.numeric I get this result:

[1] 10  9  6  8

How can I convert the coordinates in numeric format without changing the value?


longitude = structure(c(9L, 7L, 10L, 3L, 8L, 4L, 6L, 2L, 11L, 1L, 5L, 9L, 
7L, 10L, 3L, 8L, 4L, 6L, 2L, 11L, 1L, 5L), .Label = c("6.920", 
"6.922", "6.923", "6.924", "6.926", "6.936", "6.937", "6.939", 
"6.955", "6.956", "6.958"), class = "factor")

latitude = structure(c(10L, 9L, 6L, 8L, 1L, 5L, 3L, 2L, 7L, 8L, 4L, 10L, 
9L, 6L, 8L, 1L, 5L, 3L, 2L, 7L, 8L, 4L), .Label = c("50.911", 
"50.918", "50.920", "50.929", "50.930", "50.931", "50.934", "50.950", 
"50.965", "50.969"), class = "factor")

The original table luftdaten.set contains latitudes, longitudes and particulate matter values. I tried to created a grid:

coordinates(luftdaten.set) <- ~ latitude + longitude 

I also tried to create a dataframe with only the coordinates and tried to derive a grid from it:

luftdaten.grid <- data.frame(latitude, longitude) 
luftdaten.grid <- data.frame(latitude, longitude) 

Both throws the described error.

coordinates is in the SpatialTools 'sp' package.

Upvotes: 1

Views: 3717

Answers (2)

Moo
Moo

Reputation: 31

That way it works:

longitude <- as.numeric(as.character(longitude))
latitude <- as.numeric(as.character(latitude))
luftdaten.grid <- data.frame(latitude, longitude)
attach(luftdaten.grid)
coordinates(luftdaten.grid) <- ~ latitude + longitude

Upvotes: 2

Eric Watt
Eric Watt

Reputation: 3230

Assuming you're trying to get a matrix where each row is a lat/long pair:

as.matrix(cbind(as.numeric(as.character(latitude)),
                as.numeric(as.character(longitude))))

        [,1]  [,2]
 [1,] 50.969 6.955
 [2,] 50.965 6.937
 [3,] 50.931 6.956
 [4,] 50.950 6.923
 [5,] 50.911 6.939
 [6,] 50.930 6.924
 [7,] 50.920 6.936
 [8,] 50.918 6.922
 [9,] 50.934 6.958
[10,] 50.950 6.920
[11,] 50.929 6.926
[12,] 50.969 6.955
[13,] 50.965 6.937
[14,] 50.931 6.956
[15,] 50.950 6.923
[16,] 50.911 6.939
[17,] 50.930 6.924
[18,] 50.920 6.936
[19,] 50.918 6.922
[20,] 50.934 6.958
[21,] 50.950 6.920
[22,] 50.929 6.926

Upvotes: 0

Related Questions