Concatenate columns and add them to beginning of Data Frame

前端 未结 3 551
终归单人心
终归单人心 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
    
    0 讨论(0)
  • 2021-01-01 04:57

    This should do the trick

    addPrimaryKey <-function(df, cols){
    
       q<-apply(df[,cols], 1, function(x) paste(x, collapse=""))
    
       df<-cbind(q, df)
    
       return(df)
    
    }
    

    Just add in some conditional logic for your nulls

    0 讨论(0)
  • 2021-01-01 05:10

    Two other options for combining columns are dplyr::mutate() and tidyr::unite():

    library(dplyr)
    
    df %>%
      mutate(new_col = paste0(col1, col3, col4)) %>% 
      select(new_col, everything()) # to order the column names with the new column first
    
    
    library(tidyr)
    
    df %>% 
      unite(new_col, c(col1, col3, col4), sep = '', remove = FALSE)
    

    The default argument in tidy::unite() is remove = TRUE, which drops the original columns from the data frame leaving only the new column.

    0 讨论(0)
提交回复
热议问题