Reputation: 11
I have a dataframe like this:
I would like for it to be like this:
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
Upvotes: 0
Views: 218
Reputation: 14764
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
Upvotes: 1
Reputation: 9582
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
Upvotes: 1