简体   繁体   English

将数据帧中的向量拆分为列向量

[英]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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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