Using a user-defined function I have to join the lower and higher bound of confidence intervals (named as CIlow
and CIhigh
) of a selected number of columns from a data frame. The data frame has CIlow
and CIhigh
for a number of groups (named as a
, b
and c
) and for a number row (in this example just two). See below how the data frame looks like.
dataframe<-data.frame(CIlow_a=c(1.1,1.2),CIlow_b=c(2.1,2.2),CIlow_c=c(3.1,3.2),
CIhigh_a=c(1.3,1.4),CIhigh_b=c(2.3,2.4),CIhigh_c=c(3.3,3.4))
I would like to have a joined column for each group in a selected number of groups (e.g. a
, b
) among the existing ones (a
, b
and c
).
Thus, the expected output should be the following:
output<-data.frame(CI_a=c("(1.1,1.3)","(1.2,1.4)"),
CI_b=c("(2.1,2.3)","(2.2,2.4)"))
To built my own user-defined function I tried the following code:
f<-function(df,gr){
enquo_gr<-enquo(gr)
r<-df%>%
dplyr::mutate(UQ(paste("CI",quo_name(gr),sep="_")):=
sprintf("(%s,%s)",
paste("CIlow",UQ(enquo_gr),sep="_"),
paste("CIhigh",UQ(enquo_gr),sep="_")))%>%
dplyr::select(paste("CI",UQ(enquo_gr),sep="_"))
return(r)
}
However when using the above mentioned function in this way
library(dplyr)
group<-c("a","b")
dataframe<-data.frame(CIlow_a=c(1.1,1.2),CIlow_b=c(2.1,2.2),CIlow_c=c(3.1,3.2),CIhigh_a=c(1.3,1.4),CIhigh_b=c(2.3,2.4),CIhigh_c=c(3.3,3.4))
f(df=dataframe,gr=group)
I get the following error message:
Error:
expr
must quote a symbol, scalar, or call
How could I solve this issue?
PS1: This question is similar to a previous one. However, this question goes one step further because it requires selecting the columns to be merged.
PS2: I would appreciate code suggestions following the approach of this question.