Ben Hunter wrote: > > 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) > } > } > indices > } > > 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. >
It is not clear what you want. Give a simple example with input and desired output. About your function: - what's the purpose of the argument. It isn't being used in your function. - what is the argument? Character? Object? in the function body vector is used as a built-in function. Berend -- View this message in context: http://r.789695.n4.nabble.com/Putting-a-loop-in-a-function-tp3421439p3421768.html Sent from the R help mailing list archive at Nabble.com. ______________________________________________ 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.