I want to recode all the columns in my dataframe that contain the string "calcium" anywhere in the column name. So I'm trying to combine grepl with mutate from dplyr, but I get an error.
Any idea what I'm doing wrong? I hope this is possible!
The code I've tried is below using dplyr,
#Make the dataframe
library(dplyr)
fake <-data.frame(id=c(1,1,1,2,2,2,3,3,3,1,1,1,2,2,2,3,3,3),
time=c(rep("Time1",9), rep("Time2",9)),
test=c("calcium","magnesium","zinc","calcium","magnesium","zinc","calcium","magnesium","zinc","calcium","magnesium","zinc","calcium","magnesium","zinc","calcium","magnesium","zinc"),
score=rnorm(18))
df <- dcast(fake, id ~ time + test)
#My attempt
df <- df %>% mutate(category=cut(df[,grepl("calcium", colnames(df))], breaks=c(-Inf, 1.2, 6, 12, Inf), labels=c(0,1,2,3)))
#Error: 'x' must be numeric
#My second attempt
df <- df %>% mutate_at(vars(contains('calcium')), cut(breaks=c(-Inf, 1.2, 6, 12, Inf), labels=c(0,1,2,3)))
#Error: "argument "x" is missing, with no default"