-2
x<- c(62, 60, 63, 59, 63, 67)
grp1<-factor(rep(1:2))
grp2<-rep(1:3)
dat <-data.frame(x,grp1,grp2)

aaa<-function(dset,group) {
  if (length(levels(group))==2) {
    print("ccc")
  }
  else {
    print("ddd")
  }
}

I run aaa(dset=dat,group="grp1"), but the result is not "ccc". How to revise the aaa function contents and keep aaa(dset=dat,group="grp1") unchanged?

my answer:

aaa<-function(dset,group) {
  grp<-dset[,c(group)]
  if (length(levels(grp))==2) {
    print("ccc")
  }
  else {
   print("ddd")
  }
}

aaa(dset=dat,group="grp1")
stata
  • 513
  • 2
  • 6
  • 12
  • Please read some introductory material on `R`. There are many options available on the web. – mnel May 19 '14 at 00:09
  • Can you tell which introductory material on R to solve my question? – stata May 19 '14 at 00:28
  • @Urbano,In my this question.I want to keep aaa(dset=dat,group="grp1") unchanged. so it was not duplicated. – stata May 19 '14 at 00:30
  • @stata it is the same problem: "grp1" is a character vector of length one, not the column of name "grp1". By the way: `levels(dset[,group])` – Julián Urbano May 19 '14 at 00:32
  • @Urbano, Perhaps you don't know how to slove my this question,but this question must have an answer. If I have it,I will post it. – stata May 19 '14 at 00:44
  • good lord, I just gave you the answer in the comment above: *"grp1" is a character vector of length one, not the column of name "grp1". The answer is `levels(dset[,group])`* – Julián Urbano May 19 '14 at 00:53
  • @Urbano, Transform "grp1" to grp1 inside function would be a solution. – stata May 19 '14 at 01:04
  • "How to store t or F value and P value in data frame" is not an answer of this question. – stata May 19 '14 at 01:08

1 Answers1

2

The function needs to know the context of group (namely that it is a subset of dset):

aaa <- function(dset,group) {
  if (length(levels(dset[,group])) == 2) {  #this is different
    print("ccc")
  } else {
    print("ddd")
  }
}
Hugh
  • 15,521
  • 12
  • 57
  • 100