Reputation: 1277
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
Upvotes: 0
Views: 742
Reputation: 56905
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)), ... )
.
Upvotes: 5