0

I have a dataframe like this:

Dataframe

I would like for it to be like this:

What I want

How do I do it? The length of the columns will be different for each column so I think it cant be a dataframe, maybe a list of lists?

Sorry for the pictures, I'm not savvy enough to put the code in here :(

Thanks in advance

Nat

barbsan
  • 3,418
  • 11
  • 21
  • 28
Natsy
  • 11
  • Will do, thank you – Natsy Dec 03 '18 at 06:48
  • 3
    THX, avoiding duplicated questions is important. BTW, welcome at SO! Please consider [taking the tour](https://stackoverflow.com/tour) and learning [how to ask](https://stackoverflow.com/help/how-to-ask) questions. Then edit your question to give a [minimal reproducible code example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Any code/sample data should be included as text, not as a screenshot. – R Yoda Dec 03 '18 at 06:54
  • 1
    Dear SO friends, this is a new user, please drop a comment first on how to improve the question to give the new user a chance to improve the question before down voting. – R Yoda Dec 03 '18 at 06:57
  • Thank you :) I'll read it, sorry I was in a pinch. – Natsy Dec 03 '18 at 07:04

2 Answers2

1

something like this would do the job:

# data
example_df <- data.frame(col1 = c('A', 'A', 'A', 'B','B','B'),
                         col2 = 1:6)


# split into list of data.frames by value of col1
# and apply a function to get unique values of col2
lapply(
  split(example_df, example_df$col1), 
  function(x) unique(x$col2)
  )

That will return a list like this:

$A
[1] 1 2 3

$B
[1] 4 5 6
arvi1000
  • 9,393
  • 2
  • 42
  • 52
1

You could also do something like:

library(data.table)

df_new <- dcast(setDT(df), Column2 ~ Column1)[, lapply(.SD, na.omit)][!duplicated(A, B)][, Column2 := NULL]

This would give you a dataframe:

    A  B
1: 12  6
2: 23  8
3: 30 45
arg0naut91
  • 14,574
  • 2
  • 17
  • 38
  • But per OP "_The length of the columns will be different for each column so I think it cant be a dataframe,_", do dcast won't work (though it works for the example data) – arvi1000 Dec 03 '18 at 16:03