Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop last 5 columns from a dataframe without knowing specific number

Tags:

dataframe

r

I have a dataframe that is created by a for-loop with a changing number of columns.

In a different function I want the drop the last five columns.

The variable with the length of the dataframe is "units" and it has numbers between 10 an 150.

I have tried using the names of the columns to drop but it is not working. (As soon as I try to open "newframe" R studio crashes, viewing myframe is no problem).

drops <- c("name1","name2","name3","name4","name5")
newframe <- results[,!(names(myframe) %in% drops)]

Is there any way to just drop the last five columns of a dataframe without relying on names or numbers of the columns

like image 749
user3347232 Avatar asked Oct 21 '14 09:10

user3347232


People also ask

How do you drop the last 5 rows in pandas?

Drop Last Row of Pandas DataFrame Using head() Function You can also use df. head(df. shape[0] -1) to remove the last row of pandas DataFrame.


2 Answers

length(df) can also be used:

mydf[1:(length(mydf)-5)]
like image 103
rnso Avatar answered Oct 26 '22 08:10

rnso


You could use the counts of columns (ncol()):

df <- data.frame(x = rnorm(10), y = rnorm(10), z = rnorm(10), ws = rnorm(10))
# rm last 2 columns
df[ , -((ncol(df) - 1):ncol(df))]
# or
df[ , -seq(ncol(df)-1, ncol(df))]
like image 37
EDi Avatar answered Oct 26 '22 10:10

EDi