0

I am working on a project in R and, coming from Stata, am having a hard time adjusting to how for loops work. When I run this code below, I get exactly what I want. I create a new dataframe "states_1" out of an already existing dataframe "data_frame1."

states_1 <- data_frame1[["interest_over_time"]]
states_1 <- states_1[-c(1:66),]
states_1 = dcast(states_1, date ~ keyword + geo, value.var = "hits")

However, I have almost 15 dataframes and this is a shared project, so I would rather not have to repeat this for every dataframe and use a for loop instead. However, the code below tells me that I am trying to treat a function like a dataframe. Would appreciate help with how to proceed

for(i in 1:13) {
  states[i] <- data_frame[i][["interest_over_time"]]
  states[i] <- states[i][-c(1:66),]
  states[i] = dcast(states[i], date ~ keyword + geo, value.var = "hits")
 }
Nick Cox
  • 35,529
  • 6
  • 31
  • 47
  • Do you want **states** to be a data frame, or list of data frames? In either case you will probably want to make/initialise an empty data frame or list before the loop. – Mark Neal Apr 09 '20 at 01:02
  • I want to make 13 states dataframes, and then use cbind to group them into one. To be clear, are you saying I need to initially create 13 empty state dataframes/objects? – Tobin Brooks Apr 09 '20 at 02:03
  • I think you would make an empty list, the loop would create *state* data frames in the list, which you would then *unnest* (I think). It would be good to hear some other views on the best way to do this. – Mark Neal Apr 09 '20 at 03:39
  • It might give you a headache, but have a look at this [chapter](https://r4ds.had.co.nz/many-models.html). The rest of the book would actually be a good intro to R (with a tidyverse flavour), that chapter is one of the trickier ones, and assumes you understood some of what came before. Base R is more similar to Stata (I suspect), but if you are prepared to adjust your workflow and way of thinking, the tidyverse will reward you. – Mark Neal Apr 09 '20 at 03:46
  • Please read this to help you improving your questions and get more chance to find a solution. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example https://stackoverflow.com/help/how-to-ask. (I think this is not link to loop anyway) – timat Apr 09 '20 at 17:43

0 Answers0