Merge columns and add them to the top of the Data Frame

Noob is here to R. Trying to understand something. I need to create a function that will add a new column to the beginning of the dataset. This new column is a concatenation of values ​​in other columns that the user specifies.

Imagine this is a dataset called myDataSet:

col_1    col_2    col_3    col_4
bat      red      1        a
cow      orange   2        b
dog      green    3        c

The user can use the following function:

addPrimaryKey(myDataSet, cols=c(1,3,4))

to get the result of a new dataset with columns 1, 3 and 4, combined into a column with the name ID and added to the beginning, for example:

ID        col_1    col_2    col_3    col_4
bat1a     bat      red      1        a
cow2b     cow      orange   2        b
dog4c     dog      green    3        c

This is the script I was working on, but I looked at it for so long, I think I made some mistakes. I cannot figure out how to correctly get the column numbers from the arguments in the insert function.

addPrimaryKey <- function(df, cols=NULL){

  newVector = rep(NA, length(cols)) ##initialize vector to length of columns

  colsN <- as.numeric(cols)

  df <- cbind(ID=paste(
    for(i in 1:length(colsN)){
      holder <- df[colsN[i]]
      holder
    }
  , sep=""), df) ##concatenate the selected columns and add as ID column to df
df
}

Any help would be greatly appreciated. Many thanks

+3
2

paste0 , do.call:

do.call(paste0, mydf[c(1, 3, 4)])
# [1] "bat1a" "cow2b" "dog3c"

, , - :

addPrimaryKey <- function(inDF, cols) {
  cbind(ID = do.call(paste0, inDF[cols]),
        inDF)
}

interaction:

interaction(mydf[c(1, 3, 4)], drop=TRUE)
# [1] bat.1.a cow.2.b dog.3.c
# Levels: bat.1.a cow.2.b dog.3.c
+12

addPrimaryKey <-function(df, cols){

   q<-apply(df[,cols], 1, function(x) paste(x, collapse=""))

   df<-cbind(q, df)

   return(df)

}

+1

All Articles