子集不同数据类型的列表

时间:2021-10-28 16:54:22

I have a list of different data types (factors, data.frames, and vectors, all the same length or number of rows), What I would like to do is subset each element of the list by a vector (let's call it rows) that represents row names.

我有一个不同数据类型的列表(因子,data.frames和向量,所有相同的长度或行数),我想做的是通过向量对列表的每个元素进行子集(让我们称之为行)表示行名称。

If it was a data.frame() I would:

如果是data.frame()我会:

x <- x[rows,] 

If it was a vector() or factor() I would:

如果是vector()或factor(),我会:

x <- x[rows]

So, I've been playing around with this:

所以,我一直在玩这个:

x <- lapply(my_list, function(x) ifelse(is.data.frame(x), x[rows,], x[rows]))

So, how do I accomplish my goal of getting a list of subsetted data?

那么,我如何实现获取子集数据列表的目标呢?

1 个解决方案

#1


1  

I think this is YAIEP (Yet Another If Else Problem). From ?ifelse:

我认为这是YAIEP(还有另一个问题)。来自?ifelse:

ifelse returns a value with the same shape as test which is filled with elements selected from either yes or no depending on whether the element of test is TRUE or FALSE.

ifelse返回一个与test相同形状的值,该值填充了从yes或no中选择的元素,具体取决于test元素是TRUE还是FALSE。

See the trouble? Same shape as test.

看到麻烦?与测试相同的形状。

So just do this:

所以这样做:

l <- list(a = data.frame(x=1:10,y=1:10),b = 1:10, c = factor(letters[1:20]))

rows <- 1:3

fun <- function(x){
    if (is.data.frame(x)){
        x[rows,]
    }
    else{
        x[rows]
    }
}

lapply(l,fun)

#1


1  

I think this is YAIEP (Yet Another If Else Problem). From ?ifelse:

我认为这是YAIEP(还有另一个问题)。来自?ifelse:

ifelse returns a value with the same shape as test which is filled with elements selected from either yes or no depending on whether the element of test is TRUE or FALSE.

ifelse返回一个与test相同形状的值,该值填充了从yes或no中选择的元素,具体取决于test元素是TRUE还是FALSE。

See the trouble? Same shape as test.

看到麻烦?与测试相同的形状。

So just do this:

所以这样做:

l <- list(a = data.frame(x=1:10,y=1:10),b = 1:10, c = factor(letters[1:20]))

rows <- 1:3

fun <- function(x){
    if (is.data.frame(x)){
        x[rows,]
    }
    else{
        x[rows]
    }
}

lapply(l,fun)