Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a vector to data.frame, one column for each unique value

We are given a vector, like this:

x <- c(1,2,1,5,2,1,2,5,1)

What we need is a data.frame say y having number of rows equal to length(x) and number of columns equal to length(unique(x)), that means one column per unique item in x, such that y[i,j]==TRUE if and only if the ith element of x is the jth unique item of x (assigned to column j):

y <- data.frame("1"=x==1, "2"=x==2, "5"=x==5, check.names=F)

A simple way to perform this is:

y <- setNames(data.frame(sapply(unique(x), function(i) x==i)), unique(x))

Do you have a better idea (i.e. a particular function)?

like image 230
Ali Avatar asked Jan 22 '26 11:01

Ali


1 Answers

If you can live with a binary representation instead of a logical representation of your data, I would just use table:

y <- table(seq_along(x), x)

To get a data.frame, use as.data.frame.matrix:

as.data.frame.matrix(y)
#   1 2 5
# 1 1 0 0
# 2 0 1 0
# 3 1 0 0
# 4 0 0 1
# 5 0 1 0
# 6 1 0 0
# 7 0 1 0
# 8 0 0 1
# 9 1 0 0
like image 147
A5C1D2H2I1M1N2O1R2T1 Avatar answered Jan 25 '26 04:01

A5C1D2H2I1M1N2O1R2T1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!