[R] accessing variables inside a function, inside a loop
jim holtman
jholtman at gmail.com
Sun Feb 27 22:18:26 CET 2011
A quick look says you are passing N_Male in which is a vector of
values, but you are trying to use it as if it were a character value
in:
y <- DATA[[y]]
try calling it with
comp.plot(i,"N_male",DATA=water)
Also get out of the habit of using 'attach'; it can lead to other issues.
On Sun, Feb 27, 2011 at 3:48 PM, Sacha Viquerat <tweedie-d at web.de> wrote:
> dear list!
> I KNOW this has been answered a million times before. But, as some might
> remember from their "freelance" times as a statistic consultant, sometimes
> you're blinded by the facts. I KNOW I have seen this problem solved, but due
> to the mental blockade i have been suffering from the last 3 hours, I can
> neither find the answer on the mailing list nor on google. I wrote a
> function to plot one continuous variable against an abundance of fish, the
> data is called water. however, my data covers 9 parameters, and since I am
> lazy as hell, I decided to write a for loop to pass all the variables to the
> function. as usual, the variables and the data frame cannot be found inside
> the function.
>
> water<-read.csv("Henni/water-abundance2.csv",sep="\t",header=T)
> source("functions.R")
> attach(water)
>
> names(water):
> [1] "site" "sample" "temp" "pH" "DO" "BOD"
> [7] "COD" "no3" "no2" "po4" "N_male" "N_female"
>
> vars<-names(water)[3:10]
>
> par(mfrow=c(4,2))
> for (i in vars)
> {
> comp.plot(i,N_male,DATA=water)
> }
>
> comp.plot<-function(parameter,y,DATA){ #this is actually in functions.R
> x<-DATA[[parameter]]
> y<-DATA[[y]]
> plot(y~parameter)
> }
>
> and of course, this doesn't work. I am really frustrated by now, since I
> have gathered all I could recollect from my past 2 years of R experience but
> still, I was not able to find a solution. I'm really dizzy right now, but
> since I will not be able to go to sleep unless I have found the answer to
> this problem, I urge someone to shed some light on my trivial problem! I
> will promise not to post this question ever again, but for now, I'm just
> stuck!
>
> Thanks in advance and humble apologies to all that feel offended by my post!
>
> ______________________________________________
> 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
Data Munger Guru
What is the problem that you are trying to solve?
More information about the R-help
mailing list