# 获取列表中最长的元素(Get the longest element of a list)

``` 假设你有一个data.frames列表
```dfs <- list(
a = data.frame(x = c(1:4, 7:10), a = runif(8)),
b = data.frame(x = 1:10, b = runif(10)),
c = data.frame(x = 1:10, c = runif(10))
)
```
现在我想提取列表中最长的data.frame或data.frames。 怎么样？
我被困在这一点上：
```library(plyr)
lengths <- lapply(dfs, nrow)
longest <- max(lengths)
```Suppose you have a list of data.frames like
```dfs <- list(
a = data.frame(x = c(1:4, 7:10), a = runif(8)),
b = data.frame(x = 1:10, b = runif(10)),
c = data.frame(x = 1:10, c = runif(10))
)
```
I would now like to extract the longest data.frame or data.frames in this list. How?
I am stuck at this point:
```library(plyr)
lengths <- lapply(dfs, nrow)
longest <- max(lengths)
```原文：https://stackoverflow.com/questions/34747185```

## 最满意答案

``` R中有两个内置函数可以解决你的问题，我认为：

`which.max` ：返回列表中等于最大值的第一个元素的索引 ```> which.max(lengths)
[1] 2
```
哪个函数返回所有TRUE的索引在这里： ```> which(lengths==longest)
[1] 2 3
```

然后，您可以将列表子集化为所需的元素：
```dfs[which(lengths==longest)]
```
将在你的例子中返回b和c。 There are two built-in functions in R that could solve your question in my opinion:

`which.max`: returns the index of the first element of your list that is equal to the max ```> which.max(lengths)
[1] 2
```
which function returns all indexes that are TRUE Here: ```> which(lengths==longest)
[1] 2 3
```

Then you can subset you list to the desired element:
```dfs[which(lengths==longest)]
```
will return b and c in your example.```
2017-02-15

## 为什么max（Operator）不返回最长的列表？(Why does max (Operator) not return the longest list?)

F＃按元素逐个比较列表。 因为'B' > 'A'所以它认为第一个列表>第二个（字典顺序）并打破进一步比较。 您可以使用列表上的.Length属性来比较长度。 像这样，例如; let longest = if xs.Length > ys.Length then xs else ys 结果： val longest : char list = ['A'; 'B'] F# compares lists element by element. As 'B' > 'A' so it consider ...

## 获取列表中最长的元素(Get the longest element of a list)

R中有两个内置函数可以解决你的问题，我认为： which.max ：返回列表中等于最大值的第一个元素的索引 > which.max(lengths) [1] 2 哪个函数返回所有TRUE的索引在这里： > which(lengths==longest) [1] 2 3 然后，您可以将列表子集化为所需的元素： dfs[which(lengths==longest)] 将在你的例子中返回b和c。 There are two built-in functions in R that could ...