Removing Rows from a Single Column Frame

When I try to delete the last row from a single data frame of a column, I get the vector back instead of a data frame:

> df = data.frame(a=1:10) > df a 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 > df[-(length(df[,1])),] [1] 1 2 3 4 5 6 7 8 9 

The behavior I'm looking for is what happens when I use this command in a two-column data frame:

 > df = data.frame(a=1:10,b=11:20) > df ab 1 1 11 2 2 12 3 3 13 4 4 14 5 5 15 6 6 16 7 7 17 8 8 18 9 9 19 10 10 20 > df[-(length(df[,1])),] ab 1 1 11 2 2 12 3 3 13 4 4 14 5 5 15 6 6 16 7 7 17 8 8 18 9 9 19 

My code is generic, and I do not know a priori whether the data frame will contain one or more columns. Is there an easy way to solve this problem that will allow me to delete the last row no matter how many columns exist?

+5
r dataframe rows subset
Jul 12 2018-10-12T00:
source share
1 answer

Try adding drop = FALSE :

 R> df[-(length(df[,1])), , drop = FALSE] a 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 
+13
Jul 12 2018-10-12T00:
source share



All Articles