0

I have a dataframe(master) that has some variables which i have stored in the list below:

cont<-list("Quantity","Amt_per_qty","Trans_tax","Total_trans_amt")
catg<-list("Gender","Region_code","SubCategory")

I am trying to create a function where I can access the variables from dataframe and perform some function on them, though x and val in below function seems to resolve, how can I access the variables using the $ sign inside function

univar<-function (x){
                 for (val in cont){
                   print (val)
                   n<-nrow(x$val) }

                      print (n)  }
univar(master)

Its returning NULL, I tried even with n<-nrow(x[,val]), that also don't seem to work.

4
  • Use [[ instead of $ Commented Dec 2, 2016 at 10:17
  • not working either ( Commented Dec 2, 2016 at 10:18
  • You have a list, you need c Commented Dec 2, 2016 at 10:19
  • nrow(x) or length(x[[val]]) Commented Dec 2, 2016 at 10:20

2 Answers 2

2
  i) x[val] returns a data.frame
 ii) x[,val,drop = TRUE] returns a vector
iii) x[[val]] shall return as a vector. Advantage of this is : it also works with data.tables

n <- nrow(x) or length(x[[val]])
Sign up to request clarification or add additional context in comments.

Comments

0

The reason is that the OP created a list, it could be unlisted and then use [

cont <- unlist(cont)
univar<-function(x){
             for (val in cont){
               print (val)
               n<-nrow(x[[val]]) }

                  print (n)  }
univar(master)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.