[R] Putting a loop in a function

From: Ben Hunter <bjameshunter_at_gmail.com>
Date: Fri, 01 Apr 2011 17:39:14 -0700

I'm stuck here. The following code works great if I just use it on the command line in a 'for' loop. Once I try to define it as a function as seen below, I get bad results. I'm trying to return a vector of column indices based on a short string that is contained in a selection (length of about 70) of long column names that changes from time to time. Is there an existing function that will do this for me? The more I think about this problem, the more I feel there has to be a function out there. I've not found it.

ind <- function(col, string, vector){ # this is really the problem. I don't feel like I'm declaring these arguments properly.   indices <- vector(mode = 'numeric') # I am not entirely confident that this use is necessary. Is indices <- c() okay?   for (i in 1:length(col)){
    num <- regexpr(str, col[i])
    if (num != -1){

         indices <- c(vector, i) # I've also had success with indices <- append(indices, i)


ind(d[,'Column.I.want'], 'string', 'output.vector')

Am I wrong here? I've read that the last statement in the function is what it will return, and what I want is a vector of integers.



        [[alternative HTML version deleted]]

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. Received on Sat 02 Apr 2011 - 00:43:20 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 02 Apr 2011 - 08:30:26 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive