1

I have a dataset that look something like this:

groupA <- rbinom(n=50,size=1,prob=0.5)
groupB <- rbinom(n=50,size=1,prob=0.5)
groupC <- rbinom(n=50,size=1,prob=0.5)
groupD <- rbinom(n=50,size=1,prob=0.5)
dtTest <- cbind(groupA, groupB, groupC, groupD)

where 0 means "no" and 1 means "yes".

Now, i want to create a table with a column Group and another column answer, stating yes or no.

How can this be done ?

I tried the melt function and data.table group by, but keep getting error.

Nneka
  • 1,764
  • 2
  • 15
  • 39
  • Tidyverse answer: `tibble(groupA, groupB, groupC, groupD) |> pivot_longer(everything(), names_to = "group", values_to = "answer") |> mutate(answer = if_else(as.logical(answer), 'yes', 'no'))` – andrew_reece Mar 03 '23 at 19:19

2 Answers2

1

Try tidyverse / tidyr:

library(tidyverse)
library(tidyr)
df <- dtTest %>% as_tibble() %>% 
  pivot_longer(everything(), names_to = "groups", values_to = "values") %>% 
  mutate(answer = ifelse(values == 0, "no", "yes" ))
Manoj Kumar
  • 5,273
  • 1
  • 26
  • 33
0

We may use stack on the data.frame converted - cbind by default returns a matrix and not a data.frame. Instead, we may directly use data.frame(groupA, groupB, ...)

out <- stack(as.data.frame(dtTest))[2:1]
names(out) <- c("Group", "answer")
out$answer <- c("no", "yes")[out$answer + 1]

-output

> head(out)
   Group answer
1 groupA     no
2 groupA     no
3 groupA    yes
4 groupA     no
5 groupA     no
6 groupA     no

For data.table::melt, we may specify the measure as the column names, (after converting to data.table - as.data.table)

library(data.table)
melt(as.data.table(dtTest), measure = colnames(dtTest), 
   variable.name = "Group", value.name = "answer")[, 
  answer := c("no", "yes")[answer + 1]][]

-output

   Group answer
  1: groupA     no
  2: groupA     no
  3: groupA    yes
  4: groupA     no
  5: groupA     no
 ---              
196: groupD    yes
197: groupD    yes
198: groupD    yes
199: groupD    yes
200: groupD     no
akrun
  • 874,273
  • 37
  • 540
  • 662