Job Mangelmans
Job Mangelmans

Reputation: 19

Is it possible to use a function in replace() in R?

I am new to R and would like to see if there is a more elegant and quicker way to replace some data in a vector, when the replacement is conditional and the new value is based on a formula. Just putting in the formula in replace() gives an error, as the size of the replacement vector (i.e. size of the whole vector) is larger than the number of replacement (i.e. a subset of the vector)

This for loop works, but is pretty slow:

A <- df$v2/df$v1
for(i in 1:length(A))  {
    if (is.na(A[i]) & !is.na(df$v3[i])) {
        A[i] <- df$v3[i]/df$v1[i]
    }
}

The following doesn't work and I understand why (the replacement needs to be of the same size as the object being replaced), but haven't found a nicer solution than the for loop above:

A <- replace(A,is.na(A) & !is.na(df$v3),df$v3/df$v1)

It gives the following error: Warning message: In replace(.... number of items to replace is not a multiple of replacement length

Upvotes: 0

Views: 128

Answers (1)

Hong Ooi
Hong Ooi

Reputation: 57697

Don't see why replace is necessary:

A <- with(df, v2/v1)
repl <- is.na(A) & !is.na(df$v3)
A[repl] <- with(df[repl, ], v3/v1)

Alternatively, since what you're doing is calculating v2/v1 unless v2 is missing and v3 is not, in which case use v3/v1:

A <- with(df, ifelse(!is.na(v2), v2/v1, v3/v1))

Upvotes: 1

Related Questions