Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为R中列表中的每个向量提取第一个元素_R_List_Vector - Fatal编程技术网

为R中列表中的每个向量提取第一个元素

为R中列表中的每个向量提取第一个元素,r,list,vector,R,List,Vector,在R中有更多的列表,我只想为每个向量提取第一个元素。pb是因为列表的长度不同 `[[13]] start end [1,] 274 284 [[14]] start end [1,] 275 285 [2,] 786 796 [3,] 1297 1307` 在这个例子中,我想让向量1获得:274和275,而对于向量2:786和NA 我试过: 没用。因为对于第一个列表,我得到的是285,而不是NA。 这只是一个例子,我有将近8000个不同长度的列表 有什

在R中有更多的列表,我只想为每个向量提取第一个元素。pb是因为列表的长度不同

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

[[14]]
     start  end
[1,]   275  285
[2,]   786  796
[3,]  1297 1307`
在这个例子中,我想让向量1获得:
274和
275,而对于向量2:
786和
NA
我试过:

没用。因为对于第一个列表,我得到的是
285
,而不是
NA
。 这只是一个例子,我有将近8000个不同长度的列表

有什么想法吗


谢谢。

您可以检查矩阵中的行数:

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)
get_vec=n)x[n,1]NA)
}

vector1您可以检查矩阵中的行数:

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)
get_vec=n)x[n,1]NA)
}

vector1您可以使用基于
tryCatch
的矢量化函数

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

数据:


dn您可以使用基于
tryCatch
的矢量化函数

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

数据:

dn
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