Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexing an entire row with `[` as a function

Tags:

r

I would like to use `[` as a function argument in lapply to index full rows. It is fairly straightforward to do this with individual elements:

lapply( list(iris, mtcars), `[`, 1, 3 )
# [[1]]
# [1] 1.4
#
# [[2]]
# [1] 160

However, I can't seem to figure out the prefix equivalent to indexing an entire row of a data frame:

lapply( list(iris, mtcars), `[`, 1 )     # Seems to index columns
lapply( list(iris, mtcars), `[`, i=1 )   # ...same?

I know I can always define a new function

lapply( list(iris, mtcars), function(x) {x[1,]} )   # Desired behavior

but I was wondering if there's a way to get the equivalent of x[1,] in prefix form.

like image 348
Artem Sokolov Avatar asked Sep 07 '19 15:09

Artem Sokolov


People also ask

Can you INDEX match an entire row?

Generally, we can lookup a single cell only. However using the INDEX and MATCH formula helps us to perform a lookup on an entire row. This helps a lot to analyze data effective and efficiently.


1 Answers

You can do:

lapply(list(iris, mtcars), "[", 1, )

[[1]]
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa

[[2]]
          mpg cyl disp  hp drat   wt  qsec vs am gear carb
Mazda RX4  21   6  160 110  3.9 2.62 16.46  0  1    4    4

The blank space after 1, is dedicated to column(s). As you want an entire row, it is blank. If you do:

lapply(list(iris, mtcars), "[", 1, 1)

it returns:

[[1]]
[1] 5.1

[[2]]
[1] 21

that is the first row of the first column.

like image 190
tmfmnk Avatar answered Oct 04 '22 00:10

tmfmnk