Hi,
It's not clear about the pattern in your rownames.
In the for() loop, I guess you need rownames(df) instead of df.

Using an example dataset (Here the rownames may be different)
set.seed(59)
 x <- as.data.frame(matrix(rnorm(110),ncol=2))

set.seed(24)
row.names(x) <- paste0(row.names(x),Reduce(`paste0`,lapply(1:2,function(x) 
sample(letters,55,replace=TRUE))))

set.seed(435)
df <- as.data.frame(matrix(sample(200,300*20,replace=TRUE),ncol=20))
set.seed(34)
row.names(df) <- 
paste0(sample(1:55,300,replace=TRUE),Reduce(`paste0`,lapply(1:2,function(x) 
sample(letters,300,replace=TRUE))))
 gl1 <- sapply(rownames(x),function(i) 
grep(paste0(gsub("\\d+","",i),"$"),rownames(df)))
 gl1[2]
#$`2fl`
#[1] 128
rownames(df[128,])
#[1] "31fl"

A.K.




Hi, I'm having trouble using grep with a variable. When I do this it works 
fine: 

grep("^hb$", rownames(df))
[1] 9359 

but what I really want to do is use the rownames of 1 data frame
 (x) to extract the position of that same rowname in a larger data frame
 (df). How can I do this for say all of the rownames in x? The positions
 should be stored in a variable called g. 

dim(x)
[1] 55  2 

dim(df)
[1] 13000    19 

I've tried this but it does not seem to work. 

for(i in rownames(x)){ 
    g <- grep(paste("^",i,"$",sep=""), df) 
} 

any ideas? 


______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to