Home > other >  Transforming a nxm array into 1xm array in R to populate a dataframe
Transforming a nxm array into 1xm array in R to populate a dataframe

Time:03-09

I have a dataframe with columns

cols <- c("X1", "X2", "X3", "X4", "X5", "X6", "X7", "X8")

Now I am using combn() function to get all possible k-subsets, i.e. k = 4.

combs <- combn(cols, 4)

What I get with class(combs) is

[1] "matrix" "array"

And this is stored as chr [1:280] behaving like a matrix, so by writing combs[, 1:5] I get i.e.

     [,1] [,2] [,3] [,4] [,5]
[1,] "X1" "X1" "X1" "X1" "X1"
[2,] "X2" "X2" "X2" "X2" "X2"
[3,] "X3" "X3" "X3" "X3" "X3"
[4,] "X4" "X5" "X6" "X7" "X8".

Now, I would like to transform it into an array (or a list) such that I have only one row and for each column I have a vector made of values in each column, so, for the first two columns it would go like this:

                [,1]                       [,2]
[1,] c("X1", "X2", "X3", "X4")   c("X1", "X2", "X3", "X5")

EDIT! I need it to create a dataframe that looks like this:

             X1                 X2
1  c("X1", "X2", "X3", "X4")    a
2  c("X1", "X2", "X3", "X5")    b
.
.
.

Where a,b are some constants I populate my dataframe with.

CodePudding user response:

Perhaps we can try this

t(combn(cols, 4, list))

CodePudding user response:

Here is another option with tidyverse:

library(tidyverse)

output <- tribble(~ X1,
                  cols) %>%
  mutate(X1 = map(X1, ~ combn(.x, 4, FUN = paste, simplify = F))) %>%
  unnest(X1) %>%
  group_by(X1) %>% 
  mutate(X2 = stringi::stri_rand_strings(1, 1, "[a-z]"))

Output

head(as.data.frame(output))

              X1 X2
1 X1, X2, X3, X4  z
2 X1, X2, X3, X5  c
3 X1, X2, X3, X6  c
4 X1, X2, X3, X7  k
5 X1, X2, X3, X8  z
6 X1, X2, X4, X5  y

CodePudding user response:

Here is a base R approach:

combo <- apply(combs, 2, list)
NewDF <- data.frame(Col1=1:70)
NewDF$combo <- combo
head(NewDF)
  Col1          combo
1    1 X1, X2, X3, X4
2    2 X1, X2, X3, X5
3    3 X1, X2, X3, X6
4    4 X1, X2, X3, X7
5    5 X1, X2, X3, X8
6    6 X1, X2, X4, X5

CodePudding user response:

You can get list output directly from combn by specifying simplify = FALSE:

combs <- combn(cols, 4, simplify = FALSE)
combs
# [[1]]
# [1] "X1" "X2" "X3" "X4"
# 
# [[2]]
# [1] "X1" "X2" "X3" "X5"
# 
# [[3]]
# [1] "X1" "X2" "X3" "X6"
# ...

You can put these in a data frame column:

df = data.frame(id = seq_along(combs))
df[["combs"]] = combs

## access an element
df$combs[[3]]
# [1] "X1" "X2" "X3" "X6"
  • Related