takeITeasy
takeITeasy

Reputation: 360

subsetting a data frame according to specific pattern

matrix <- matrix(grep("a",rownames(fru))

for (l in matrix){
  s <- fru[l,]  
  sa <- rbind(s)
  View(sa)
}


fru is a data frame. matrix is a list of rownumbers of specific rows in fru (rows that contain a special pattern in their rownames).


fru <- data.frame(variable1=c("8","67","89"),variable2=c("89","89","0"),variable3=c("89","890","89")
row.names(fru,c("c1","a2","c3","a4"))

I want a data frame with all rows that have an "a" in their rownames. I want all columns to be in that new data frame.

The loop gives me a bunch of data frames that are all the same: It is the last specific row (in fru, that means row a4 with all four "variable" columns).

How do I get a subset of specific rows of fru? The specifity of the rows is a pattern that is part of their rownames (that is why I can´t use subset() function).

What is wrong with that loop?

Thank you in advance ;)

Upvotes: 1

Views: 544

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101149

Of course you are able to use subset, i.e.,

res <- subset(fru,grepl("a",rownames(fru)))

Upvotes: 0

GKi
GKi

Reputation: 39647

You can use grep to find rownames with a and subset them with [].

fru[grep("a",rownames(fru)),]
#   v1 v2 v3
#a2  2  2  3
#a4  4  2  3

Data:

fru <- data.frame(v1=1:4,v2=2,v3=3, row.names=c("c1","a2","c3","a4"))
fru
#   v1 v2 v3
#c1  1  2  3
#a2  2  2  3
#c3  3  2  3
#a4  4  2  3

Upvotes: 1

Related Questions