[R] R function data variable name argument
Sarah Goslee
sarah.goslee at gmail.com
Fri Nov 9 20:06:17 CET 2012
Hi,
If you move the read.csv statement outside the function and instead
pass the data as an argument, then you can provide a reproducible
example using dput(head(drugs, 20)) or a similar fake dataset. It's
really hard to debug code without knowing what kind of data it is
supposed to act upon.
In the meantime, have you tried running the code line by line outside
the function to see what happens at each step, including setting the
loop variable to 1, 2, 3, etc and seeing what happens?
Sarah
On Fri, Nov 9, 2012 at 12:38 PM, Le Lait, Marie-Claire
<Marie-Claire.LeLait at rmpdc.org> wrote:
> Hello fellow R-ers,
> I have spent some time on this and it is driving me NUTS! I am sure there is a solution, so please help.
>
> I am trying to create a function that will plot different lines for subsets of a dataset. For example, I am trying to look at different drug groups (drug2), let's say 1,2,3,4, and 5. The data has 2 different rates, college students and high school students (var names cs and hs). Here is my code:
>
> stuff<-function(druglist, rate, yaxislabel)
> {
> drugs<-read.csv("drugs.csv", header=T)
> druglist.data<-drugs[which(drugs$drug2 %in% druglist),]
> par(xpd=NA,oma=c(3,0,3,16),usr=c(1,40,0,0.5))
> #print(rate)
> plot(druglist.data$counter, druglist.data$rate, type="n", xlab="Quarter", ylab="yaxislabel", xaxt='n', yaxt='n', main="", ylim=c(0,.5))
>
> for (i in druglist)
> {
> line<-druglist.data[which(druglist.data$drug2==i),]
> lines(line$counter, line$rate, type='l')
> print(line$drug2)
> print(line$counter)
> print(line$rate)
> }
> }
>
> stuff(c(1, 2, 3, 4, 5), 'cs')
> stuff(c(1, 2, 3, 4, 5), 'hs')
>
>
> I have played with attach and detach so I don't have to use the $, but that did not work. I also read several posts suggesting substitute(), but I don't know where to use it. The code works until the for loop, but at this point the line$rate outputs as 'NULL'. Please help.
>
> Thanks!
>
> Claire, MS
> Statistical Research Specialist
>
--
Sarah Goslee
http://www.functionaldiversity.org
More information about the R-help
mailing list