Reputation: 6262
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?
Upvotes: 0
Views: 11168
Reputation: 99331
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
Upvotes: 3
Reputation: 887128
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
Upvotes: 1
Reputation: 5369
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
.
Upvotes: 4