JGLM JGLM - 2 months ago 12
R Question

R: Creating a function to merge two columns

Sorry if something similar to my question has already been posted, I couldn't found what I am looking for.

I have a dataset with two columns, one with mean values and one with sd values.
I would like to create a third columns that would be "mean (sd)". I have been able to do it using paste() without problems.
Now what I would like to do is creating a function to do it on various datasets/variables. I have the following:


data$z <- paste(data[,x]," (",data[,y],")",sep = "")

merge.meansd(data,"a", "b","c")

I get the following that I can't solve:

Coercing LHS to a list

Any idea or solutions to my problem ?



If you want to include a character column in the same data structure as a couple of numeric vectors, you almost certainly want to use a data frame rather than a matrix (as @RichScriven comments above).

merge.meansd <- function(dd,x,y,z) {
   dd <- as.data.frame(dd)
   dd[[z]] <- paste0(data[,x]," (",data[,y],")")
   ## or dd[[z]] <- sprintf("%f (%f)",dd[,x],d[,y])

ddm <- merge.meansd(data,"a","b","c")


  • I think you wanted to return the entire data frame, not just the merged column?
  • you can't use $-indexing with the value of a variable, you need [[ ]]