Concatenate columns and add them to beginning of Data Frame

前端 未结 3 652
终归单人心
终归单人心 2021-01-01 04:52

Noob here to R. Trying to figure something out. I need to build a function that adds a new column to the beginning of a dataset. This new column is a concatenation of the va

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-01 04:57

    paste0 works fine, with some help from do.call:

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

    Your function, thus, can be something like:

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

    You may also want to look at 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
    

提交回复
热议问题