简体   繁体   中英

Extract the first element for every vector in a list in R

I have more lists in R and I want to extract only the first element for every vector. The pb is that the length of the list isn't the same.

`[[13]]
     start end
[1,]   274 284

[[14]]
     start  end
[1,]   275  285
[2,]   786  796
[3,]  1297 1307`

In this example, I want for vector 1 to obtain: 274 and 275 and for vector 2: 786 and NA I tried:

Data$Variable2 = lapply(Data$Position,"[",2:2)
Data$Variablex = sapply(Data$Position,"[[",2)
Data$Variablex = map(Data$Position,2)

Nothing work. Because for the first list I obtain 285 instead NA . And this is only a example, I have almost 8000 list with different lengths.

Any idea?

Thank you.

You can check for number of rows in the matrix:

get_vec <- function(Data, n) {
  sapply(Data, function(x) if(nrow(x) >= n) x[n, 1] else NA)
}

vector1 <- get_vec(Data$Position, 1)
vector2 <- get_vec(Data$Position, 2)

You may use a vectorized function based on tryCatch .

ext <- Vectorize(
  function(x, i) tryCatch(unname(x[i, 1]), error=function(e) rep(NA, length(i))),
  vectorize.args="i")

Usage examples:

sapply(L, ext, 1)
# [1] 274 275 275
sapply(L, ext, 3)
# [1]   NA 1297   NA
sapply(L, ext, 1:3)
#      [,1] [,2] [,3]
# [1,]  274  275  276
# [2,]   NA  786  787
# [3,]   NA 1297   NA
lapply(L, ext, c(1, 3))
# [[1]]
# [1] 274  NA
# 
# [[2]]
# [1]  275 1297
# 
# [[3]]
# [1] 276  NA

Data:

dn <- list(NULL, c("start", "end"))
L <- list(matrix(c(274, 284), 1, dimnames=dn),
     matrix(c(275, 786, 1297, 285, 796, 1307), ncol=2, dimnames=dn),
     matrix(c(276, 787, 286, 797), ncol=2, dimnames=dn))

L
# [[1]]
# start end
# [1,]   274 284
# 
# [[2]]
# start  end
# [1,]   275  285
# [2,]   786  796
# [3,]  1297 1307
# 
# [[3]]
# start end
# [1,]   276 286
# [2,]   787 797

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