Rspacer
Rspacer

Reputation: 2429

How to assign values in new column based on condition in another column using if and non-if functions in R

I have a data set "data". If the variable (in long form) contains A1 or D1, assign "1:5 dil" in data$dilutions column. If it has B1 or C1 assign "1:10 dil". How can I do this using both if and non-if functions?

In the original data I have lots of assignments, hence I want to see if non-if conditions work better

cycles <- c(1:100)
A1 <- c(1:100)
B1 <- c(100:199)
C1 <- c(5:104)
D1 <- c(0:99)
data <- data.frame("cycles" = cycles, "A1" = A1, "B1" = B1, "C1" = C1, "D1" = D1)


library(reshape2)
data <- melt(data, id.vars=c("cycles"))
data$dilutions <- if(data$variable=="A1"|"D1" <- "1:5 dil", data$variable== "B1" | "C1" <- "1:10 dil")

Upvotes: 0

Views: 104

Answers (1)

phalteman
phalteman

Reputation: 3532

As mentioned in the comments, your use of the if statement is incorrect. Here are two approaches, one making use of ifelse() and one using direct assignments on subsets.

data$dilutions <- ifelse(data$variable == "A1" | data$variable == "D1", "1:5 dil", "1:10 dil")

If you have more than these two possible outcomes, you may need to chain your ifelse statements (i.e., use another ifelse() for the else part of the call.

Otherwise, you can use direct assignments, like so:

data$dilutions[data$variable=="A1" | data$variable== "D1"] <- "1:5 dil"
data$dilutions[data$variable=="B1" | data$variable== "C1"] <- "1:10 dil"

Upvotes: 1

Related Questions