1

I am doing lots of operations on a dataframe to reshape my data.

Often, I use subsets like

trx[which(trx$Currency == "EUR"),]$ExchangeOriginal<- 1

However, when I applying my functions to data where certain subsets do not exist, the function will fail. For example, if there are no

trx$Currency

values that are "EUR".

What are smart ways to handle this? Is there something like

On Error Resume next
user670186
  • 2,588
  • 6
  • 37
  • 55
  • I found http://stackoverflow.com/questions/2589275/r-how-to-tell-lapply-to-ignore-an-error-and-process-the-next-thing-in-the-list but this is a complex work around – user670186 Jul 01 '13 at 00:12
  • Are you using this within a function? Also, it would be useful if you posted some data to work with – alexwhan Jul 01 '13 at 00:25

2 Answers2

3

For your particular example, selecting the column to have its value set inside the bracket operator will avoid the issue:

trx <- data.frame(Currency="XXX", ExchangeOriginal=30)
trx[trx$Currency == "EUR", "ExchangeOriginal"] <- 1  # Does nothing

(Also note that since you can use boolean expressions for subsetting, you don't need "which".)

Answering your second question, the try and tryCatch functions could be used here to recover from the error, but it seems better to avoid the error in the first place if possible:

try(trx[trx$Currency == "EUR", ]$ExchangeOriginal <- 1)
David F
  • 1,255
  • 9
  • 12
0

Another approach using within:

within(trx, if(exists("Currency")) ExchangeOriginal[Currency == "EUR"] <- 1)
Ferdinand.kraft
  • 12,579
  • 10
  • 47
  • 69