Starting from a dataframe in R like the following (df):
year_1 <- c('James','Mike','Jane', NA)
year_2 <- c('Evelyn', 'Jackson', 'James', 'Avery')
year_3 <- c('Harper', 'Avery', NA, NA)
df <- data.frame(year_1, year_2, year_3)
...I would like convert it into something like df1 (of course I have hundreds of elements in my original dataframe, so I can't go manually)
names <- c('James','Mike','Jane','Evelyn', 'Jackson', 'Avery', 'Harper')
year_1 <- c('YES','YES','YES', 'NO', 'NO', 'NO', 'NO')
year_2 <- c('YES','NO','NO', 'YES', 'YES', 'YES', 'NO')
year_3 <- c('NO','NO','NO', 'NO', 'NO', 'YES', 'YES')
df_1 <- data.frame(year_1, year_2, year_3)
rownames(df_1) <- names
I have tried to:
- convert all elements of df into a string vector with unique elements
- construct the structure of df1 taking the names of step 1)
- try to fill df1 with a loop (here is where I am not able to build a proper loop that makes the trick)
Any idea?
Thanks!!
as.data.frame.matrix(table(stack(df))).