Reputation: 456
I have this data
M1 M2 M3 UCL
1 2 3 1.5
I would like to make new columns with this condition:
If M1 is more than UCL, MM1 will be "UP" and otherwise "NULL"
If M2 is more than UCL, MM2 will be "UP" and otherwise "NULL"
If M3 is more than UCL, MM3 will be "UP" and otherwise "NULL"
M1 M2 M3 UCL | MM1 MM2 MM3
1 2 3 1.5 | NULL UP UP
But I have several M column (like M1~M1005) so that I would like to make some code such as mutate_each and mutate_at. How do I use the function using mutate and ifelse in order to make new columns under a particular condition?
Upvotes: 2
Views: 4358
Reputation: 2019
Here is a simple dplyr
solution. Note that it is easier to add a suffix to the new variables e.g. to get M1_M
rather than MM1
. However, you can set the colnames
afterwards if you were keen to rename them (see e.g. here on how to do that).
I show the result as a tibble
so you can see the column types. Note that once a new column has a both an UP
and an NA
in it, it will change from a logical type to a character type.
library(dplyr)
textdata <- "M1 M2 M3 UCL
1 2 3 1.5"
mydf <- read.table(text = textdata, header = T)
mydf %>%
mutate_at(vars(starts_with("M")), funs(M = ifelse(. > UCL, "UP", NA))) %>%
tibble::as.tibble()
# A tibble: 1 x 7
M1 M2 M3 UCL M1_M M2_M M3_M
<dbl> <dbl> <dbl> <dbl> <lgl> <chr> <chr>
1 1 2 3 1.5 NA UP UP
Upvotes: 5
Reputation: 25435
With base R:
dt <- read.table(text="M1 M2 M3 UCL
1 2 3 1.5",header=T)
ncols <- ncol(dt)
dt <- cbind(dt, ifelse(subset(df, select=M1:M3) > dt[,"UCL"], "UP", "NULL"))
colnames(dt)[ncols:ncol(dt)] = paste0("M", colnames(dt)[ncols:ncol(dt)])
result:
M1 M2 M3 UCL MM1 MM2 MM3
1 1 2 3 1.5 NULL UP UP
Upvotes: 1