[R] Problem with Grep Under Loop

jim holtman jholtman at gmail.com
Mon Oct 6 14:02:18 CEST 2008


Seems to work fine for me.  You need to read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
You did not provide 'source', so I created one and it seems to work.
So I have to conclude you have something wrong in your data.

> hm_acc <- c("XM_528056","AB002296")
> source <- data.frame(V1=c("XM_528056","AB002296"), V2=1:2)
> for (i in 1:length(hm_acc)){
+
+    hm_acc_id <- as.character(hm_acc[i])
+    print(hm_acc_id)
+
+    hm_allk <- grep(hm_acc_id,source$V1)
+    hm_all <- source[hm_allk,]
+
+    print(hm_all)
+ }
[1] "XM_528056"
         V1 V2
1 XM_528056  1
[1] "AB002296"
        V1 V2
2 AB002296  2
>


On Mon, Oct 6, 2008 at 7:37 AM, Gundala Viswanath <gundalav at gmail.com> wrote:
> Dear all,
>
> I have no problem with this individual grep command:
>
>> datk <- grep("XM_528056", source$V1)
>> dat2 <- source[datk,]
>> print(dat2)
>             V1      V2   V3 V4      V5      V6         V7
> 35995 XM_528056 panTro2 chr8  + 1775569 1896107 Chimpanzee
>
>
> BUT, when I run them under the loop it gives this error:
>
>
>> hm_acc <- c("XM_528056","AB002296")
>> for (i in 1:length(hm_acc)){
> +
> +    hm_acc_id <- as.character(hm_acc[i])
> +    print(hm_acc_id)
> +
> +    hm_allk <- grep(hm_acc_id,source$V1)
> +    hm_all <- source[hm_allk,]
> +
> +    print(hm_all)
> + }
>
> [1] "XM_528056"
> [1] V1 V2 V3 V4 V5 V6 V7
> <0 rows> (or 0-length row.names)
> [1] "AB002296"
> [1] V1 V2 V3 V4 V5 V6 V7
> <0 rows> (or 0-length row.names)
> .....
>
> What's wrong with my way of using grep?
> Please advice.
>
>
> - Gundala Viswanath
> Jakarta - Indonesia
>
> ______________________________________________
> R-help at 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?



More information about the R-help mailing list