R nested for loop combining rows within one column

Viewed 206

I'm interested in looping over a dataframe and getting all combinations (without repetition) of a certain variable.

This can be stored in a list, and later appended to a new dataframe as a column. I would like to achieve this using R, but Python would be ok as well.

My current data:

    idx     A         B        C
    1     name1    val_x1    val_y1
    2     name2    val_x2    val_y2
    3     name3    val_x3    val_y3
    ...
    10    name10   val_x10   val_y10

Since n-1 = 9 and 9+8...+1 = 45 my desired data would be, as a list:

    c("name1_name2","name1_name3","name1_name4",...,"name9_name10")

and later on as a dataframe:

    idy     D
    1    name1_name2
    2    name1_name3
    3    name1_name4
    ...
    45   name9_name10

I thought to make a list out of the desired data, with a nested for loop, but it doesn't work as I'm probably doing something (multiple things?) wrong.

    i <- 1
    j <- 2
    k <- 1
    new_list <- c()

    while (k < 45)
        while (i < 11){
            while (j < 10){
                new_list[[k]] <- paste(df$A[i], df$A[j], sep="_")
                j <- j + 1
                k <- k + 1
            }
            i <- i + 1
        }

This is not working as said, any tips are welcome.

PS. I'm relatively new, thanks for your patience :)

1 Answers
Related