JGLM
JGLM

Reputation: 3

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:

a=round(runif(20,0,50),2)
b=round(runif(20,0,1),2)
data<-cbind(a,b)

merge.meansd<-function(data,x,y,z){
  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 ?

Thanks

Upvotes: 0

Views: 79

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226557

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])
   return(dd)
}

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

Also:

  • 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 [[ ]]

Upvotes: 1

Related Questions