1

When I have a vector of vectors in R, how do I select a vector that contains one element from each outer vector?

For example, given this data:

> data<-c("1,2","3,4","5,6")
> data<-strsplit(data,",")
> data
[[1]]
[1] "1" "2"

[[2]]
[1] "3" "4"

[[3]]
[1] "5" "6"

How do I get a vector containing (1,3,5) and nothing else?

Thanks!

4

6 回答 6

8

一种方法是使用sapply

> sapply( data, "[[", 1 )
[1] "1" "3" "5"
于 2012-11-12T13:29:20.153 回答
1

您可以使用以下递归函数,即使您的列表深度超过 2 级,该函数也可以使用

getElemsR <- function(dat, Index, Lev=2)  {
  if ((Lev <- (Lev - 1)) > 1)  {
    inds <- seq(length(dat[[1]]))
    dat <- unlist(lapply(inds, function(i) getElemsR(dat, i, Lev)), recursive=F)
  } 
  sapply(dat, "[[", Index, USE.NAMES=T, simplify=F)
}

# get the 2nd element of every 2nd-Level list
getElemsR(myData, 3)  # Lev=2 by default

# get the 2nd element of every 3rd-Level list
getElemsR(myData, 2, 3)

# if needed as a vector:
unlist(getElemsR(myData, 2, 3))


或者,如果您的列表只有两层深,您可以使用简单的 sapply 正如@Romain 指出的那样。您可以将其包装在一个函数中

getElems <- function (dat, Index)  {
  sapply(dat, "[[", Index)
}

# get the 2nd element of every 2nd-level list
getElems(data1, 2)


样本数据

data1 <- lapply(1:3, paste0, c("A","B"))
data2 <- lapply(4:6, paste0, c("A","B"))
names(data1) <- names(data2) <- c("_sub1", "_sub2", "_sub3")
myData <- list(Lev1A=data1, Lev1B=data2)
于 2012-11-12T16:52:41.740 回答
1

这将返回一个数字向量,因为 read.table 会将其测试应用于列:

> read.table(text=data, sep=",")$V1
[1] 1 3 5

为向量使用名称“数据”可能是不明智的,因为它也是基本函数的名称。

于 2012-11-12T15:34:01.317 回答
1

由于您的示例使用strsplit我假设这是您首先获取数据集的方式?如果是这样,使用正则表达式也可以,并且可能会稍微快一些。例如

data <- c("1,2","3,4","5,6")

# Remove everything after ,:
gsub(",.*","",data)

# Select first number:
regmatches(data,regexpr("\\d+",data))
于 2012-11-12T18:27:41.303 回答
1

另一种解决方案:

unlist(data)[c(TRUE, rep(FALSE, length(data[[1]]) - 1))]

[1] "1" "3" "5"
于 2012-11-12T16:11:44.823 回答
0

或这个 :-) :

foo<- unlist(data)
matrix(foo,nrow=length(data),byrow=TRUE)[,1] 

[1] "1" "3" "5"
于 2012-11-12T15:06:34.063 回答