Is there a way to select a subset of a dataframe consisting of all those rows with rownames *except* from a subset of rownames to be excluded? Example: > a <- data.frame(x=1:10,y=10:1) > a <- a[order(a$y),] # to make rownames differ visually > a[8,] x y 3 3 8 > a["8",] x y 8 8 3 > a[-8,] x y 10 10 1 9 9 2 8 8 3 7 7 4 6 6 5 5 5 6 4 4 7 2 2 9 1 1 10 > a[-"8",] Error in -"8" : invalid argument to unary operator -- is there a similar exclusion operator or simple way? So far the best I can do is > a[setdiff(rownames(a),"8"),] x y 10 10 1 9 9 2 7 7 4 6 6 5 5 5 6 4 4 7 3 3 8 2 2 9 1 1 10 Cheers, Alexy
Prof Brian Ripley
2008-Oct-12 06:20 UTC
[R] subsetting dataframe by rownames to be excluded
On Sat, 11 Oct 2008, Alexy Khrabrov wrote:> Is there a way to select a subset of a dataframe consisting of all those rows > with rownames *except* from a subset of rownames to be excluded? Example:Yes: DF[is.na(match(row.names(DF), exclude_me)), ]> >> a <- data.frame(x=1:10,y=10:1) >> a <- a[order(a$y),] # to make rownames differ visually > >> a[8,] > x y > 3 3 8 > >> a["8",] > x y > 8 8 3 > >> a[-8,] > x y > 10 10 1 > 9 9 2 > 8 8 3 > 7 7 4 > 6 6 5 > 5 5 6 > 4 4 7 > 2 2 9 > 1 1 10 > >> a[-"8",] > Error in -"8" : invalid argument to unary operator > > -- is there a similar exclusion operator or simple way? So far the best I > can do is > >> a[setdiff(rownames(a),"8"),] > x y > 10 10 1 > 9 9 2 > 7 7 4 > 6 6 5 > 5 5 6 > 4 4 7 > 3 3 8 > 2 2 9 > 1 1 10 > > Cheers, > Alexy-- Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595
Prof Brian Ripley <ripley <at> stats.ox.ac.uk> writes:> Yes: DF[is.na(match(row.names(DF), exclude_me)), ]Assuming everything is possible in R: would it be possible to make the below work without breaking existing code? a <- data.frame(x=1:10) rownames(a) = letters[1:10] exclude = c("a","c") a[is.na(match(row.names(a), exclude)), ] # not really that easy to remember a[-c(1,3),] # In analogy.... a[-c(exclude),] #invalid argument to unary operator Dieter