ibilgen
ibilgen

Reputation: 480

Why length function does not work correct in R?

Following R code gives the cars which are in Type Small. But length function returns 6 instead of 13. Why is that?

> fuel.frame[fuel.frame$Type=="Small",]            

            row.names Weight  Disp. Mileage     Fuel  Type
1      Eagle.Summit.4     30   0.97      33 3.030303 Small
2       Ford.Escort.4     28 114.00      33 3.030303 Small
3      Ford.Festiva.4     23   0.81      37 2.702703 Small
4       Honda.Civic.4     27   0.91      32 3.125000 Small
5     Mazda.Protege.4     29 113.00      32 3.125000 Small
6    Mercury.Tracer.4     27   0.97      26 3.846154 Small
7     Nissan.Sentra.4     27   0.97      33 3.030303 Small
8    Pontiac.LeMans.4     28   0.98      28 3.571429 Small
9     Subaru.Loyale.4     27 109.00      25 4.000000 Small
10     Subaru.Justy.3     24   0.73      34 2.941176 Small
11   Toyota.Corolla.4     28   0.97      29 3.448276 Small
12    Toyota.Tercel.4     25   0.89      35 2.857143 Small
13 Volkswagen.Jetta.4     28 109.00      26 3.846154 Small

> length(fuel.frame[fuel.frame$Type=="Small",])

[1] 6

Upvotes: 3

Views: 4636

Answers (2)

user1317221_G
user1317221_G

Reputation: 15441

I thought it might help to give a bit of an explanation as to thy your getting your result. Your asking the length of the data.frame not the vector. Since the data.frame has 6 columns that explains your result.

this asks for the vector specifically:

length(fuel.frame$Type[fuel.frame$Type=="Small"])

and so does this:

length(fuel.frame[fuel.frame$Type=="Small",][,1])

or use nrow instead of length as already suggested.

Upvotes: 3

Timo
Timo

Reputation: 5390

length gives in this case the number of columns in the data frame. You can instead use nrow or ncol to get the number of rows or number of columns respectively:

nrow(fuel.frame[fuel.frame$Type=="Small",])

Another example using iris dataset:

> d = head(iris)
> d
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa
> nrow(d)
[1] 6
> ncol(d)
[1] 5
> dim(d)
[1] 6 5

Upvotes: 5

Related Questions