0

I would like to create a very simple function that will take the dataframe and row number as arguemnts, and then return a dataframe without that row. So if I have:

1 ben
2 adrian
3 bill
4 matthew

After calling remove(3,df) I will get:

1 ben
2 adrian
3 matthew

Anyone can help out?

7
  • 1
    Are you aware of the fact that you can use e.g. df[-3,] to remove row 3 from the output? (or in case of multiple rows to be removed: df[-c(1:2),])? Commented Aug 15, 2014 at 11:08
  • 1
    @beginneR, he will need , drop=F too in order to keep it in a data.frame structure, but that's basically it Commented Aug 15, 2014 at 11:10
  • I want to permantently remove it from the dataframe and then save it to rda file Commented Aug 15, 2014 at 11:11
  • @LucasSeveryn, to permanently remove it, use df <- df[-3,, drop=FALSE] and then save it as you wish. Commented Aug 15, 2014 at 11:12
  • @beginneR, actually akrun already demonstrated it Commented Aug 15, 2014 at 11:13

3 Answers 3

4

This function can be written as a one-liner (albeit without error checking):

remrow <- function(x, rows) x[-rows,, drop = FALSE]

Here's your data:

dat <- data.frame(A = 1:4, B = 5:8)
rownames(dat) <- c("ben", "adrian", "bill", "matthew")

remrow(dat, 2) will strip out the "adrian" row, while remrow(dat, 1:2) will remove both the "ben" and "adrian" rows.

Note that is.data.frame(remrow(dat, 1)) evaluates to TRUE.

Sign up to request clarification or add additional context in comments.

Comments

3

It seems like this is all you really need

> removeRows <- function(rowNum, data) {
      newData <- data[-rowNum, , drop = FALSE]
      rownames(newData) <- NULL
      newData
  }
> dat
#        V2
# 1     ben
# 2  adrian
# 3    bill
# 4 matthew
> removeRows(3, dat)
#        V2
# 1     ben
# 2  adrian
# 3 matthew

Comments

1

If df is the dataset

fun1 <- function(data, rowN){
 indx <- !(seq_len(nrow(data)) %in% rowN)
 data1 <- data[indx,, drop=F]
 row.names(data1) <- seq_len(nrow(data1))
 data1
 }

fun1(df, 3)
#       V1
#1     ben
#2  adrian
#3 matthew

fun1(df,1:2)
#       V1
#1    bill
#2 matthew

4 Comments

Why are you using row.names here? All he wants is a row number. It is quite possible that the row.names won't fit the row number. I don't think anything else but data[-rowN,, drop=F] is needed in this function
@David Arenburg, I changed row.names to 1:nrow(data). Yes, you are right. there may be cases with different rownames.
@beginneR. You are absolutely correct. Thanks for your comments. Updated the code.
rownames(data) <- NULL will reset the row names to a sequence also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.