如何将矢量数据转换为数据框或矩阵

时间:2019-04-24 15:49:23

标签: r dataframe matrix vector

我有这个数据集:

ID <- c("0001", "0003", "0002","0004","0005")
YourName <- c("Juan", "Pedro", "Ana", "Alejandra","Alex")
GenderPeople <- c("Male","Male","Female","Female","Male")

DF <- data.frame(ID, YourName, GenderPeople)

我想将“ GenderPeople”列转换为如下所示的矩阵(或数据框):

    ID  YourName GenderPeople_Male GenderPeople_Female
  0001      Juan                 1                   0
  0003     Pedro                 1                   0
  0002       Ana                 0                   1
  0004 Alejandra                 0                   1
  0005      Alex                 1                   0

非常感谢您的帮助。

问候!

2 个答案:

答案 0 :(得分:2)

我们可以在创建1秒的列后使用FILE *fnew; int num; //i do have a lot of code before to get the 'num' value from where I want, don't bother it; char filename[]= "bookX.txt"; filename[4]=num+1; fnew = fopen(filename,"w"); fclose(fnew);

spread

答案 1 :(得分:2)

library(dummies)

dummy.data.frame(DF, names = "GenderPeople", sep = "_")

#     ID  YourName GenderPeople_Female GenderPeople_Male
# 1 0001      Juan                   0                 1
# 2 0003     Pedro                   0                 1
# 3 0002       Ana                   1                 0
# 4 0004 Alejandra                   1                 0
# 5 0005      Alex                   0                 1