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)?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With