Reputation: 7526
I have a list of coordinates in which the x coordinate is at [,1]
and the y coordinate is at [,2]
(sample data below). As I am new working with lists in R, I am wondering how to add a third "column" to the list.
I have tried accessing the elements of the list with test.route[[1]][[1]]
, test.route[[1]][[2]]
but am not able to do so.
Just as an example, how would one add a column of zeros in [,3]
in test.route
?
> str(test.route)
List of 1
$ :List of 1
..$ :List of 1
.. ..$ : num [1:33, 1:2] -79.9 -79.9 -79.9 -79.9 -79.9 ...
> dput(test.route)
list(list(list(structure(c(-79.9298866666667, -79.9299016666667,
-79.9299016666667, -79.9298716666667, -79.929865, -79.9299, -79.9299766666667,
-79.930025, -79.930125, -79.9301816666667, -79.930165, -79.9301183333333,
-79.9301283333333, -79.9301966666667, -79.93024, -79.9303133333333,
-79.93012, -79.9298366666667, -79.9295716666667, -79.9292916666667,
-79.9290283333333, -79.9287816666667, -79.92838, -79.9281916666667,
-79.9279933333333, -79.927765, -79.927495, -79.9272033333333,
-79.9269016666667, -79.92651, -79.92651, -79.92651, -79.92651,
43.2555883333333, 43.2554766666667, 43.2554766666667, 43.2554716666667,
43.2555033333333, 43.255585, 43.2557366666667, 43.255925, 43.2563183333333,
43.256565, 43.25686, 43.2572183333333, 43.257535, 43.2577966666667,
43.2580533333333, 43.2585666666667, 43.2586866666667, 43.2587133333333,
43.25873, 43.25877, 43.258835, 43.258925, 43.2591666666667, 43.2592883333333,
43.2594233333333, 43.2595433333333, 43.2596533333333, 43.2597333333333,
43.2597833333333, 43.259895, 43.2598966666667, 43.2598966666667,
43.2598966666667), .Dim = c(33L, 2L)))))
Upvotes: 1
Views: 46
Reputation: 887851
We can use rapply
to go through the nested list
and create a column
test.route1 <- rapply(test.route, function(x) cbind(x, 0), how = "list")
str(test.route1)
#List of 1
# $ :List of 1
# ..$ :List of 1
# .. ..$ : num [1:33, 1:3] -79.9 -79.9 -79.9 -79.9 -79.9 ...
Upvotes: 1