数据框(R)中所有列的合并组合

时间:2019-01-13 23:37:18

标签: r

我想串联列而不重复列组合。我在下面有一个例子来说明我要做什么

让我们假设我有一个包含3列的数据框,我想基于原始列创建更多列(2的组合),将其作为两列的串联

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

现在,我希望将以下内容作为新列的输出(显示前2行的结果以及所需的列名)

V1_V2  V1_V3    V2_V3
A_NO   A_Alpha  No_Alpha
A_Yes  A_Yes    Yes_Yes

我试图用以下函数创建一个循环,但我有5个新列而不是3个列,例如V1_V3与V3_V1重复。我正在尝试弄清楚如何解决此问题。另外,如果有更好的解决方案

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)
    }
  }
}

2 个答案:

答案 0 :(得分:1)

不需要循环。可以使用sapplycombnpaste将其向量化。根据基准测试,它也比使用循环快约20倍。

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"

答案 1 :(得分:0)

修改您的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)