4

I am extracting specific rows from a list of data frames in R and would like to have those rows assembled into a new data frame. As an example, I will use the iris data:

data(iris)
a.iris <- split(iris, iris$Species) 
b.iris <- lapply(a.iris, function(x) with(x, x[3,]))

I want the return from lapply() to be arranged into a single data frame that is in the same structure as the original data frame (e.g., names(iris)). I have been looking at the plyr package but cannot find the right code to make this work. Any assistance would be greatly appreciated!

Brian

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Brian P
  • 1,496
  • 4
  • 25
  • 38

1 Answers1

5

You can use do.call() with rbind() and simplify your lapply() call.

a.iris <- split(iris, iris$Species)
b.iris <- do.call(rbind, lapply(a.iris, `[`, 3, ))
b.iris
##            Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
## setosa              4.7         3.2          1.3         0.2     setosa
## versicolor          6.9         3.1          4.9         1.5 versicolor
## virginica           7.1         3.0          5.9         2.1  virginica

> all.equal(names(iris), names(b.iris))
## [1] TRUE

Or course, you could have also used tapply() to find the third row per group.

iris[tapply(seq_len(nrow(iris)), iris$Species, `[`, 3), ]
#     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
# 3            4.7         3.2          1.3         0.2     setosa
# 53           6.9         3.1          4.9         1.5 versicolor
# 103          7.1         3.0          5.9         2.1  virginica
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245