0

I have a data frame:

  L1 2020 NA
1  1    0  0
2  2    1  0
3  3    1  0

I want to delete first and last column, to get dataframe like this:

2020 
1  0 
2  1 
3  1 

I tried: 1)

df <- df[,-c(1,ncol(df))]

or 2)

df <- subset(df, select = -c(1,ncol(df)))

For both I get result:

[1] 0 1 1

So I guess it changed data frame into vector. How can I delete these columns to keep it as a data frame?It is important for me to keep it like this. I don't have this problem when there are more columns. It changes only when one column is supposed to be left.

beechy
  • 101
  • 8
  • You can give `[` a `drop = FALSE` argument to tell it to not "drop" unneeded dimensions. `df[,-c(1,ncol(df)), drop = FALSE]` will work. (This is a confusing bit about subsetting data frames). – Gregor Thomas Nov 12 '20 at 14:10
  • Alternately, when subsetting columns, if you use `[` without a row argument, you will always get a data frame result. So `df[-c(1,ncol(df))]` will also work. (This is treating the data frame like a list of columns - which is how the data frame class is implemented.) – Gregor Thomas Nov 12 '20 at 14:11

1 Answers1

1

After specifiing the columns in the square-brackets, add ,drop=FALSE right after it.

The drop-argument is TRUE by default and you are struggling with this default.

df <- data.frame(a=1:10,b=1:10)
df[,1] #R simplifies to a vector via implicit drop=TRUE default
df[,1,drop=FALSE] #dataframe-structure remains
Jonas
  • 1,760
  • 1
  • 3
  • 12