0

I would like to R to the following: if LocID is equal to 3,4,7,8, 14 then data$newConc is equal to data$conc/2 else data$newConc <- data$conc # else keep conc the same

data$newConc <- if(data$LocID == c(3,4,7,8,14))
data$conc/2 else data$conc

str(data)
 $ LocID     : int  1 2 3 4 5 6 7 8 9 10 ...
 $ time      : int  1 1 1 1 1 1 1 1 1 1 ...
$ conc      : num  0.03695 0.0155 0.00738 0.00753 0.01795 ...

Warning: the condition has length > 1 and only the first element will be used

1
  • 1
    The R code you've given isn't valid...no balanced brackets? Did you mean ifelse? Commented Mar 13, 2012 at 4:59

1 Answer 1

5

As far as I can tell from your code (which won't even run, due to a missing closing bracket?) you're trying to do (pseudocode):

foreach row in data
    if row$LocID is one of 3, 4, 7, 8, or 14
    THEN set row$newConc to row$conc/2
    ELSE set row$newConc to row$conc

To do this you use ifelse.

Also, if you want to test if a value is equal ot 3, 4, 7, 8 or 14, then don't use == -- that will return a vector of booleans, and if requires a single boolean, hence your error.

Either use data$locID %in% c(3,4,7,8,14) to return a single TRUE/FALSE, or use any(data$locID == c(3,4,7,8,14)) to turn the vector of booleans into a single boolean:

You're comparing a scalar to a vector, and so your output is a vector. An if statement only takes in a single boolean (not a vector of booleans).

Either use data$locID %in% c(3,4,7,8,14) to return a single TRUE/FALSE, or use any(data$locID == c(3,4,7,8,14)) to turn the vector of booleans into a single boolean:

data$newConc <- ifelse( data$locID %in% c(3,4,7,8,14),
                        data$conc/2,
                        data$conc )

Alternatively I could have used ifelse( any(data$locID == c(3,4,7,8,14)), ... ).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.