user13710936
user13710936

Reputation: 53

Convert dataframe to a list in R

I have a data.frame like this:

df<-data.frame(x=c(1,2,3),y=c(4,5,6),row.names=c("x1","x2","x3")
colnames(df) <- c("y1","y2")

I want to have a list that looks like this:

C1 C2 Values
x1 y1 1
x1 y2 4
x2 y1 2
x2 y2 5
x3 y1 3
x3 y2 6

I am not sure what I can do. I tried melt function. But it didn't return what I want.

Upvotes: 2

Views: 59

Answers (3)

akrun
akrun

Reputation: 886938

An option with base R

as.data.frame.table(as.matrix(df))
#   Var1 Var2 Freq
#1   x1   y1    1
#2   x2   y1    2
#3   x3   y1    3
#4   x1   y2    4
#5   x2   y2    5
#6   x3   y2    6

Upvotes: 0

tmfmnk
tmfmnk

Reputation: 39858

One base R option could be:

setNames(data.frame(stack(df), rownames(df)), c("Values", "C2", "C1"))

  Values C2 C1
1      1 y1 x1
2      2 y1 x2
3      3 y1 x3
4      4 y2 x1
5      5 y2 x2
6      6 y2 x3

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388797

You can add rownames as column and then use pivot_longer to get data in long format.

df %>%
  tibble::rownames_to_column('C1') %>%
  tidyr::pivot_longer(cols = -C1, names_to = 'C2')

# A tibble: 6 x 3
#  C1    C2    value
#  <chr> <chr> <dbl>
#1 x1    y1        1
#2 x1    y2        4
#3 x2    y1        2
#4 x2    y2        5
#5 x3    y1        3
#6 x3    y2        6

Upvotes: 2

Related Questions