I have a data table[1000+, 4]
.
One of the columns has 5 levels
and I want to make these 5 levels into 5 new columns.
Any suggestions?
I have a data table[1000+, 4]
.
One of the columns has 5 levels
and I want to make these 5 levels into 5 new columns.
Any suggestions?
We extract the levels
from the column of interest ('ColN'), convert to list
and assign that to five 'new' columns.
df1[paste0("new", 1:5)] <- as.list(levels(df1$ColN))
head(df1,2)
# ColN Col2 Col3 new1 new2 new3 new4 new5
#1 C 7 a A B C D E
#2 A 4 b A B C D E
levels(df1$ColN)
#[1] "A" "B" "C" "D" "E"
data
set.seed(48)
df1 <- data.frame(ColN= sample(LETTERS[1:5], 10,
replace=TRUE), Col2= sample(10), Col3= letters[1:10])