loop over the data frame and create new lines

advertisements

I have a data set that has two columns. AccountName and AccountNumber. It has 35 rows. I want to create a new dataframe with AccountName, AccountNumber, and LocationNumber. LocationNumber is stored in another data frame with 1 column that has 350 rows.

so basically for each account name and number, foreach location number, add another row with the account name + number + location number. so if I have 35 account numbers and 350 locations, the end goal is to have 12,250 rows. i've tried using for loop to no avail.

accounts (name | number)

STR EXP-VACATION ESTIMATE-0200900   200900
STR EXP-HOLIDAY PAY-0200920 200920
STR EXP-SICK PAY-0200930    200930
STR EXP-MISC TIME PAID,NOT WORKED-0200990   200990

locations:

Lo.702-002
Lo.702-003
Lo.702-004
Lo.702-005

end result for EACH of the account numbers

STR EXP-VACATION ESTIMATE-0200900   200900 Lo.702-002
STR EXP-VACATION ESTIMATE-0200900   200900 Lo.702-003
STR EXP-VACATION ESTIMATE-0200900   200900 Lo.702-004
STR EXP-VACATION ESTIMATE-0200900   200900 Lo.702-005

the PHP code that would produce the results I want:

foreach($accounts as $name => $number) {
    foreach($locations as $location) {
        echo sprintf("%s,%s,%s\n", $name, $number, $location);
    }
}


My solution:

acc.run <- function() {
  locFileName <- 'location-list.csv'
  accFileName <- 'account-list.csv'

  locations <- read.csv(locFileName, sep=',', quote='\"', header=T)

  accounts <- read.csv(accFileName, sep=',', quote='\"', header=T)

  #Add row numbers
  accounts$rowNum <- 1:nrow(accounts)

  merged <- merge(accounts, locations)

  sorted <- merged[order(merged$rowNum), ]

  final <- sorted[, !(names(sorted) %in% c('rowNum'))]

  # Random file extension to prevent duplicate/overwriting
  rExt <- paste(round(runif(6,10,100)), sep='', collapse='')

  write.csv(final, paste('accounts-concat', rExt, '.csv', sep='', collapse=''), row.names=F)
}

let me know how I can improve this?