Re: [R] Putting a loop in a function

From: Berend Hasselman <bhh_at_xs4all.nl>
Date: Sat, 02 Apr 2011 02:51:49 -0500 (CDT)

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 &lt;- function(col, string, vector){ # this is really the problem. I
> don't
> feel like I'm declaring these arguments properly.
> indices &lt;- vector(mode = 'numeric') # I am not entirely confident
> that
> this use is necessary. Is indices &lt;- c() okay?
> for (i in 1:length(col)){
> num &lt;- regexpr(str, col[i])
> if (num != -1){
> indices &lt;- c(vector, i) # I've also had success with indices
> &lt;-
> 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:

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_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 - 07:57:18 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 - 10:20: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