-2

I have a data frame of 166 people which I would like to convert to a binary matrix. So in the data frame it looks like the following:

Photo

I am just wondering what code could I use to convert this to binary i.e 1/0s

A = absent
N = no 
Y = yes 

All for votes

Any help would be appreciated !

ganchito55
  • 3,559
  • 4
  • 25
  • 46
  • It would help if you provided a [reproducible example](http://stackoverflow.com/a/5963610/2921990). What have you tried so far? Also, you have three values in your data but want to convert them into 0s and 1s -- which values should become 0 and which should become 1? – Kara Woo Feb 14 '17 at 16:03
  • I haven't used R a lot before so the only example I can give is the following link I provided. I have tried to do the following: (df<-data.frame(id=1:166,vote=sample(c("yes","no","absent"),166,replace=TRUE)))----- model.matrix(~.-1,df) – XeroPhobous Feb 14 '17 at 16:06
  • And because I haven't been told I am going on the assumption that yes = 1 and absent and no = 0 – XeroPhobous Feb 14 '17 at 16:07

1 Answers1

1

I've just created some sample data, If I understand what you are looking for correctly -

df <-matrix(sample(c("a","n","y"),166*20, replace = TRUE),166,20)
df[df == "a"]=NA
df[df == "y"]= 1
df[df == "n"] = 0    
ArunK
  • 1,731
  • 16
  • 35
  • I will try this now but just to clear up because there are 23 columns, is the 166*20 in your code just 166 people by the 23 votes i.e. in the picture it goes from v1 up to v23 – XeroPhobous Feb 14 '17 at 16:13
  • The number of columns and rows doesn't matter here. as you have 3 distinct answers "a", "y", "n". You are replacing values of columns for example where `df == "a"` is true. – ArunK Feb 14 '17 at 16:16
  • 1
    I just used it there, you are a life saver ! – XeroPhobous Feb 14 '17 at 16:18