0

I'm brand new to programming and an picking up Rstudio as a stats tool. I have a dataset which includes multiple questionnaires divided by weeks, and I'm trying to organize the data into meaningful chunks. Right now this is what my code looks like:

w1a=table(qwest1,talm1)

w2a=table(qwest2,talm2)

w3a=table(quest3,talm3)

Where quest and talm are the names of the variable and the number denotes the week. Is there a way to compress all those lines into one line of code so that I could make w1a,w2a,w3a... each their own object with the corresponding questionnaire added in?

Thank you for your help, I'm very new to coding and I don't know the etiquette or all the vocabulary.

Community
  • 1
  • 1
  • 2
    This would be much easier to answer if we had a better idea of how the data looked. Please read [how to ask good questions](https://stackoverflow.com/help/how-to-ask), then come back and edit your question. Other suggested reading: [minimal, verifiable examples](https://stackoverflow.com/help/mcve) and [reproducible questions](https://stackoverflow.com/questions/5963269/). (Also, RStudio is an interface, "R" is the stats tool. This question is about the language, not the interface, so I'm removing the `[rstudio]` tag.) – r2evans Jul 12 '18 at 19:55
  • Having numbers in your variable names is a sign that things are already off to a bad start. Related values should all be in lists in R, rather than be variables with kind of similar names. How are you creating them in the first place? – MrFlick Jul 12 '18 at 21:08

1 Answers1

1

This might do what you wanted (but not what you asked for):

 tbl_list <- mapply(table,  list(qwest1, qwest2, quest3),
                            list(talm1, talm2, talm3) )
 names(tbl_list) <-  c('w1a', 'w2a','w3a')

You are committing a fairly typical new-R-user error in creating multiple similarly named and structured objects but not putting them in a list. This is my effort at pushing you in that direction. Could also have been done via:

  qwest_lst <-  list(qwest1, qwest2, quest3)
  talm_lst <- list(talm1, talm2, talm3)
  tbl_lst <- mapply(table, qwest_lst, talm_lst)
  names(tbl_list) <-  paste0('w', 1:3, 'a')

There are other ways to programmatically access objects with character vectors using get or wget.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • for `dplyr` users, the function `lst` behaves just like `list` except that it names its items using the object names, which I've found very convenient. – moodymudskipper Jul 12 '18 at 20:34
  • Thank you! This was very helpful, it did what I needed to do. I never knew of the mapply or the names function. I appreciate your help and the education. – Absolute_Human Jul 13 '18 at 19:14
  • `mapply` lets you work through lists like they were "parallel" columns. First argument is a function and the rest of the arguments get either positionally matched or matched by name to the arguments of that function. – IRTFM Jul 14 '18 at 03:46