简体   繁体   中英

Splitting a vector in a dataframe into column vectors

I have a vector in a data frame that I want to split into many column vectors as follows:

region<- c("US","India", "France", "Greece")
id<- c(1, 2,3,4)
df1<- data.frame(region,id)

I want to split the data frame as follows:

region.US  region.India region.France region.Greece  id 
  1            0              0            0          1
  0            1              0            0          2
  0            0              1            0          3
  0            0              0            1          4

Any suggestions on how to do this?

To get exactly that output:

cbind(setNames(as.data.frame(diag(nrow(df1))), paste0("region.", df1$region)),
      df1[,"id", drop=FALSE])
#   region.US region.India region.France region.Greece id
# 1         1            0             0             0  1
# 2         0            1             0             0  2
# 3         0            0             1             0  3
# 4         0            0             0             1  4

Try this even though it is not exactly what you want.

t(table(df1))
   region
id  France Greece India US
  1      0      0     0  1
  2      0      0     1  0
  3      1      0     0  0
  4      0      1     0  0

This almost works (the order of columns isn't identical, and the column names aren't dot-separated):

df1 <- data.frame(region=c("US","India", "France", "Greece"),
                 id=1:4)
data.frame(model.matrix(~region-1,df1),id=df1$id)

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