简体   繁体   中英

Convert a categorical column in so many columns as factors in R

I have a dataframe like this one, where there might be more than one numerical column and more than one categorical column. In this case, there is only one of each class.

在此处输入图片说明

I would like to create a new data frame where new columns are created, each of them by one single factor of the initial V2 variable, as you can see here:

在此处输入图片说明

I've been searching this forum and found some questions related to mine but with boolean variables.

I am sure the code would be extraordinarily easy, but somehow I cannot find the correct one. Any help?

Use unstack()

df <- data.frame(V1 = 1:6,
                 V2 = rep(c("DC1", "DC2"), each = 3),
                 stringsAsFactors = FALSE)

unstack(df)
#  DC1 DC2
#1   1   4
#2   2   5
#3   3   6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM