Remove all rows of an R dataframe

January 13, 2011
By

[This article was first published on Brock's Data Adventure » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

I should have probably figured this out a long time ago, but as I get deeper into programming with R, I am finding the need to remove all rows from a dataframe.  I was making this alot harder than it had to be.

your.df<- your.df[which(is.na(your.df$text)), ]

Replace your.df with, your dataframe and you are good to go. For the longest time, everytime I saw an example or an answer that included which, I stayed clear. I couldn’t wrap my head how to use it.

In my own words, it returns a logical TRUE/FALSE for every “thing” in an expression. If using Excel or SPSS, think that it returns a true or false for every row in a workbook or SPSS dataset. That is fairly straightforward, but when would you use it?

If you recall, when selecting rows in a data frame using an expression (d f[ df$a == b, ]), the evaluation of the function returns a TRUE or FALSE, and only the rows with TRUE are returned. Coming from SPSS, if you select variables through the dialog box, you see a variable that is filter_$ added to the dataset, and it contains the values 0,1. This is the same thing, you just don’t ‘see’ it because R doesn’t have a native GUI. Until now, I had never once thought to tell R to return 0 rows.

I had always thought the best approach would have been something along the lines of

df$col <- NULL

which deletes the column ‘col’ from your dataset.

Sadly, I previously was using a ‘for loop’ to iterate over every row in a dataframe and do needless operations.

I have a love/hate relationship with R right now.

Filed under: How-to, R, SPSS Tagged: Dataframe, R, SPSS, Tutorial

To leave a comment for the author, please follow the link and comment on their blog: Brock's Data Adventure » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , , , ,

Comments are closed.

Search R-bloggers

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)