# What does the drop=F argument in a matrix do in R?

#1

Hello,

I have a matrix->

x=matrix(runif(9,3,10),nrow=3)
x
[,1] [,2] [,3]
[1,] 8.477339 8.833459 8.583553
[2,] 4.654282 7.649464 5.036848
[3,] 6.272135 3.469831 6.246960

If I use the command->

x[2,drop=F]

I get,

[,1] [,2] [,3]
[1,] 4.654282 7.649464 5.036848

and if I use

x[2,drop=T]

I get->
[1] 4.654282 7.649464 5.036848

What is the drop=F/T exactly doing here? Also if I use drop=F and drop=T like this, I get the same output->

x[2:3,drop=T]
[,1] [,2] [,3]
[1,] 4.654282 7.649464 5.036848
[2,] 6.272135 3.469831 6.246960
x[2:3,drop=F]
[,1] [,2] [,3]
[1,] 4.654282 7.649464 5.036848
[2,] 6.272135 3.469831 6.246960

Why is the output same here?
Thanks

#2

x[2,drop=F] is the same as x[2,]

what does drop do?

if you see ?drop

Drop Redundant Extent Information

Description

Delete the dimensions of an array which have only one level.

Usage

drop(x)
Arguments

x
an array (including a matrix).

Value

If x is an object with a dim attribute (e.g., a matrix or array), then drop returns an object like x, but with any extents of length one removed. Any accompanying dimnames attribute is adjusted and returned with x: if the result is a vector the names are taken from the dimnames (if any). If the result is a length-one vector, the names are taken from the first dimension with a dimname.

Array subsetting ([) performs this reduction unless used with drop = FALSE, but sometimes it is useful to invoke drop directly.

#3

You will see a more pronounced difference when subsetting columns:

``````x1 <- x[,1, drop=FALSE]
x1
[,1]
[1,] 7.753318
[2,] 7.546510
[3,] 9.184788

x2 <- x[,1, drop=TRUE]
x2
[1] 7.753318 7.546510 9.184788
``````

When `drop` is `FALSE`, the dimensions of the object are kept. And it is not just a cosmetic difference. They are different structures with disparate behavior in functions.

``````colSums(x1)
[1] 24.48462

colSums(x2)
Error in colSums(x2) : 'x' must be an array of at least two dimensions``````