Molia
Molia

Reputation: 311

Concatenate Combination of All Columns in a dataframe (R)

I would like to concatenate columns without repeating the column combination. I have an example below to explain what I am trying to do

Lets suppose that I have a dataframe with 3 columns and I would like to create more columns (that are a combination of 2) based on the original columns as a concatenation of two columns

Example of a df

V1 <- as.character(c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B"))
V2 <- as.character(c("No","Yes","Yes","No","No","No","Yes","Yes","Yes","No"))
V3 <- as.character(c('Alpha',"Yes",'NA','Beta','NA',"Yes",'NA',"Yes","Yes",
'Something','Else'))

df_sample <- as.data.frame(cbind(V1, V2, V3))
df_sample

Now I would like the following as the output for new columns (showing the result for the first 2 rows and the desired column names as well)

V1_V2  V1_V3    V2_V3
A_NO   A_Alpha  No_Alpha
A_Yes  A_Yes    Yes_Yes

I tried to create a loop with the following function but I have 5 new columns instead of 3 like V1_V3 is repeating with V3_V1. I am trying to figure out on how we can fix this. Also if there is a better way for the solution

str_eval=function(x) {return(eval(parse(text=x)))}

cat_cols <- c('V1','V2','V3')

for (i in (1:length(cat_cols))){
  for (j in (1:length(cat_cols))){
    if (i != j){
      col_name <- paste(colnames(df_sample)[i],"_",colnames(df_sample)[j],sep="")
      assign(col_name,
         paste(df_sample[,cat_cols[i]],'_',df_sample[,cat_cols[j]],sep=""))
      df_sample <- cbind(df_sample, str_eval(col_name))
      colnames(df_sample)[ncol(df_sample)] <- paste(col_name)
      rm(col_name)
    }
  }
}

Upvotes: 0

Views: 475

Answers (2)

hmhensen
hmhensen

Reputation: 3195

There's no need for loops. This can be vectorized using sapply and combn with paste. It's also about 20X faster than using a loop, based on a benchmark test.

cols_to_paste <- 2 #number of columns you want to paste together.
sapply(1:ncol(combn(names(df_sample), cols_to_paste)), function(x){
      do.call(paste, c(df_sample[, combn(names(df_sample), cols_to_paste)[,x]], sep="_"))} )

      [,1]    [,2]          [,3]          
 [1,] "A_No"  "A_Alpha"     "No_Alpha"    
 [2,] "A_Yes" "A_Yes"       "Yes_Yes"     
 [3,] "A_Yes" "A_NA"        "Yes_NA"      
 [4,] "A_No"  "A_Beta"      "No_Beta"     
 [5,] "A_No"  "A_NA"        "No_NA"       
 [6,] "B_No"  "B_Yes"       "No_Yes"      
 [7,] "B_Yes" "B_NA"        "Yes_NA"      
 [8,] "B_Yes" "B_Yes"       "Yes_Yes"     
 [9,] "B_Yes" "B_Yes"       "Yes_Yes"     
[10,] "B_No"  "B_Something" "No_Something"
[11,] "A_No"  "A_Else"      "No_Else"

Upvotes: 1

aashish
aashish

Reputation: 315

Modifying your soln

    V1 <- as.character(c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B"))
    V2 <- as.character(c("No","Yes","Yes","No","No","No","Yes","Yes","Yes","No"))
    V3 <- as.character(c('Alpha',"Yes",'NA','Beta','NA',"Yes",'NA',"Yes","Yes",
                         'Something'))
    V4 = 1:10
    V5 = 10:1

    df_sample <- as.data.frame(cbind(V1, V2, V3, V4, V5))
    df_sample

    str_eval=function(x) {return(eval(parse(text=x)))}

    cat_cols <- c('V1','V2','V3','V4','V5')

    for (i in (1:length(cat_cols))){
      if(i < length(cat_cols)){
      for (j in (i+1):length(cat_cols)){
          col_name <- paste(colnames(df_sample)[i],"_",colnames(df_sample)[j],sep="")
          assign(col_name,
                 paste(df_sample[,cat_cols[i]],'_',df_sample[,cat_cols[j]],sep=""))
          df_sample <- cbind(df_sample, str_eval(col_name))
          colnames(df_sample)[ncol(df_sample)] <- paste(col_name)
          rm(col_name)
        }
      }
    }

    head(df_sample)

Upvotes: 0

Related Questions