[R] Use of parantheses to force order of execution

Duncan Murdoch murdoch.duncan at gmail.com
Sun Sep 8 16:09:06 CEST 2013


On 13-09-08 6:46 AM, Ben Harrison wrote:
> Hello,
> I wish to create a copy of a data frame, but with missing values replaced
> with NAs.
>
> I thought I should be able to do it in one step using parentheses to group
> the statements and force those inside the parens to execute first:
>
> df <- (BWS6[BWS6 < -998] <- NA)
>
> But all this does is assign NA to df, as described in ?"[" for the case
> with no parens.
>
> Can I do this in some way? It's no great problem of course to have two
> separate statements, just curious.

This isn't an order of execution issue.  Your parenthesized assignment 
modifies BWS6, and that's not what you want to do.

If you convert BWS6 to a matrix instead of a dataframe, you could use

res <- ifelse(BWS6 < -998, NA, BWS6)

but ifelse doesn't work on dataframes in general.  You can do it in one 
long line with a dataframe using lapply, but it is ugly:

df <- as.data.frame( lapply(BWS6, function(col) ifelse(col < -998, NA, 
col)))

Duncan Murdoch



More information about the R-help mailing list