0

I would like to create a function to join the lower and higher bound of confidence intervals (named as CIlow and CIhigh) from a data frame. See the data frame below as example.

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))

The data frame has CIlow and CIhigh for a number of groups (named as a, b and c) and for a number of variables (in this case two, the rows of the data frame).

group<-c("a","b","c")

To build my own function I tried the following code:

f<-function(df,gr){

enquo_df<-enquo(df)
enquo_gr<-enquo(gr)

r<-df%>%
   dplyr::mutate(UQ(paste("CI",enquo_gr,sep="_")):=
                   sprintf("(%s,%s)",
                           paste("CIlow",quo_name(enquo_gr),sep="_"),
                           paste("CIhigh",quo_name(enquo_gr),sep="_")))

return(r)
}

However when using the function

library(dplyr)

group<-c("a","b","c")
    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 do not get the expected output

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)"),
                  CI_c=c("(3.1,3.3)","(3.2,3.4)"))

but the following error message:

Error: LHS must be a name or string

Do you know why? How could I solve this issue? Thanks in advance.

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
ungatoverde
  • 161
  • 12
  • 2
    What is `enquo_shortgr`? – F. Privé Jul 09 '17 at 12:20
  • Could you provide a reproducible example (i.e. provide all the data and libraries you are using plus the code)? – dvarelas Jul 09 '17 at 12:27
  • Sorry @F.Privé, the `enquo_shortgr` was a mistake when transfering the code from the real case to this example. The right name is of course `enquo_gr`. I just corrected the code in my question. – ungatoverde Jul 09 '17 at 12:35
  • @dvarelas the only package used here is `dplyr` (as written before the only used function, i.e. dplyr::mutate). Anyway, just to clarify I have added the following line in the code of my question: `library(dplyr)` – ungatoverde Jul 09 '17 at 12:37
  • 1
    Can you provide the expected output? I don't get what your function should return. – F. Privé Jul 09 '17 at 12:42
  • @F.Privé I just added the expected output to my question. Thank you for the reminder. – ungatoverde Jul 09 '17 at 12:48

1 Answers1

2

Old school solution:

res <- as.data.frame(matrix(NA_character_, nrow(dataframe), ncol(dataframe) / 2))
for (i in seq_along(group)) {
  var <- paste0("CI", c("low", "high"), "_", group[[i]])
  res[[i]] <- sprintf("(%s,%s)", dataframe[[var[[1]]]], dataframe[[var[[2]]]])
}
names(res) <- paste0("CI_", group)
F. Privé
  • 11,423
  • 2
  • 27
  • 78