0

I am trying to use a for loop to save dataframes and variable names on the way.

I have a data frame called regionmap, one of the variables (Var3) can take thousands different values, among which there are 15 of this form: "RegionMap *" where * is one of the values of the vector c:

regions <- c("A", "B"........"Z")

I need to run a loop which selects the rows in which each of these values appear, save those rows as a new data frame, transform the relative frequency in a dummy and then merge the new data frame with a bigger one aimed at collecting all of these.

The following code works, I just wanted to know whether it possible to run it 15 times substituting every "A" (both as strings to select and as names of data frames and variables) with other elements of c like in a for loop. (standard for loop does not work)

A <- regionmap[grep("RegionMap A", regionmap$Var3), ]

A$Freq[A$Freq > 1] <- 1

A$Var3 <- NULL

colnames(A) <- c( "name", "date", "RegionMap A")

access_panel <- merge(access_panel, A,by=c("name", "date"))
Antonio
  • 158
  • 1
  • 14
  • If you can add a sample of your data it makes it easier for folks to answer. Check out https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – austensen May 30 '17 at 16:08

1 Answers1

1

You don't need to name the variables differently if you are merging everything together anyway - just the column names. Something like this should do the trick...

regions <- c("A", "B"........"Z")
for(x in regions){
    mapname <- paste("RegionMap",x,sep=" ") #this is all that needs to change each time
    A <- regionmap[grep(mapname, regionmap$Var3), ]
    A$Freq[A$Freq > 1] <- 1
    A$Var3 <- NULL
    colnames(A) <- c( "name", "date", mapname)
    if(x=="A") {
      access_panel <- A #first one has nothing to merge into
    } else {
      access_panel <- merge(access_panel, A ,by=c("name", "date"))
    }
}
Andrew Gustar
  • 17,295
  • 1
  • 22
  • 32
  • 1
    Thank you very much. I explained myself poorly though, access_panel is an existing data frame where to add the others created with the loop. I removed the "if...else" part and it works perfectly. – Antonio May 30 '17 at 17:17