I have a very large data frame containing 2 levels of a factor, levels "No" and "Yes". I would like to replace the levels to numeric values, so that "No" turns into 0, and "Yes" turns into 1.
I would like to apply a function that works on the data frame.
A simple example to work on:
> df
a b c d
1 1 No Yes 1
2 2 No No 3
3 3 Yes No 123
4 4 Yes Yes 12
5 5 No Yes 231
6 6 No No 21
7 7 Yes No 21
8 8 Yes No 21
> str(df)
'data.frame': 8 obs. of 4 variables:
$ a: int 1 2 3 4 5 6 7 8
$ b: Factor w/ 2 levels "No","Yes": 1 1 2 2 1 1 2 2
$ c: Factor w/ 2 levels "No","Yes": 2 1 1 2 2 1 1 1
$ d: int 1 3 123 12 231 21 21 21
Wanted results :
> df
a b c d
1 1 0 1 1
2 2 0 0 3
3 3 1 0 123
4 4 1 1 12
5 5 0 1 231
6 6 0 0 21
7 7 1 0 21
> str(df)
'data.frame': 8 obs. of 4 variables:
$ a: int 1 2 3 4 5 6 7 8
$ b: int 0 0 1 1 0 0 1 1
$ c: int 1 0 0 1 1 0 0 0
$ d: int 1 3 123 12 231 21 21 21
Try
This could be wrapped into a function