简体   繁体   中英

How to get first element of all list elements in a matrix

I have this data set

my_coords <- structure(list(50.7642396, 6.0932425, 50.7289167, 6.1779893, 
    50.7559189, 6.1466953, 50.7980556, 6.0602183, 50.7744281, 
    6.0836151, 50.7743273, 6.1065564, c(50.764164, 50.7689394
    ), c(6.0620818, 6.0684758)), .Dim = c(2L, 7L), .Dimnames = list(
    c("lat", "lng"), NULL))

which looks like this:

    [,1]     [,2]     [,3]     [,4]     [,5]     [,6]     [,7]     
lat 50.76424 50.72892 50.75592 50.79806 50.77443 50.77433 Numeric,2
lng 6.093242 6.177989 6.146695 6.060218 6.083615 6.106556 Numeric,2

In column 7 I have very similar values and I want to get only one of those. Preferably the first.

How to do that in a generic way?

I tried lapply(my_coords , "[[", 1) . However this is not doing what I want. I could put the values back together manually but there must be a smarter way

The desired output is:

    [,1]     [,2]     [,3]     [,4]     [,5]     [,6]     [,7]    
lat 50.76424 50.72892 50.75592 50.79806 50.77443 50.77433 50.76416
lng 6.093242 6.177989 6.146695 6.060218 6.083615 6.106556 6.062082

You could extract those values using sapply (similar to what you have tried) and wrap the output in matrix

matrix(
  sapply(my_coords , "[[", 1),
  nrow = dim(my_coords)[1],
  dimnames = dimnames(my_coords)
)
#         [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
#lat 50.764240 50.728917 50.755919 50.798056 50.774428 50.774327 50.764164
#lng  6.093242  6.177989  6.146695  6.060218  6.083615  6.106556  6.062082

Another option mentioned by @RonakShah in the comments would be

my_coords[] <- sapply(my_coords , "[[", 1)

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