6

I have a list, with 3 "columns":

test = list(1:100, 1:100,1:100)

How can I access the e.g. first 10 entries of each column?

test[c(1:10),]

doesn't work. I know it works for data.frames:

as.data.frame(test)[1:10,1:3]

How do I solve this with lists?

Edit: To get an answer more general:

How do I get the entries 15 to 20 in column 1 and 3? Here is what I do for data.frames:

as.data.frame(test)[c(15:20),c(1,3)]

It seems like the indexing differs a lot between data.frames and lists.

4

3 回答 3

12

您可以使用函数lapply()head().

lapply(test,head,n=10)
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10

[[2]]
 [1]  1  2  3  4  5  6  7  8  9 10

[[3]]
 [1]  1  2  3  4  5  6  7  8  9 10

如果列表元素中的值小于n=,则显示所有值。

test = list(1:100, 1:100,1:5)
lapply(test,head,n=10)
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10

[[2]]
 [1]  1  2  3  4  5  6  7  8  9 10

[[3]]
[1] 1 2 3 4 5
于 2013-08-13T12:54:17.957 回答
3

取决于您想要的返回类型,lapply否则sapply会有用。我会[用来获取你想要的元素:

lapply( test , `[` , 1:10 )
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10

[[2]]
 [1]  1  2  3  4  5  6  7  8  9 10

[[3]]
 [1]  1  2  3  4  5  6  7  8  9 10

 sapply( test , `[` , 1:10 )
      [,1] [,2] [,3]
 [1,]    1    1    1
 [2,]    2    2    2
 [3,]    3    3    3
 [4,]    4    4    4
 [5,]    5    5    5
 [6,]    6    6    6
 [7,]    7    7    7
 [8,]    8    8    8
 [9,]    9    9    9
[10,]   10   10   10
于 2013-08-13T12:54:21.960 回答
2

如果您在一个函数中有两个或两个以上的输入,您可以使用Map很有帮助的函数:

mytest<-Map(function(x) x[1:10], test)
> mytest
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10

[[2]]
 [1]  1  2  3  4  5  6  7  8  9 10

[[3]]
 [1]  1  2  3  4  5  6  7  8  9 10
于 2013-08-13T13:13:11.507 回答