0

I have a dataframe from where I want to make the values of a column as column names, but keep the values of other columns intact. Is there an efficient way to do this is R?

Sample example

Answer   Freq   Number   Question   Perc
         7      Q1       A          1.54
Yes      243    Q1       A          53.52
No       204    Q1       A          44.93

I want to transform this to the following

Yes  No  " "  Number   Question   Yes_Perc   No_Perc   ""_Perc  
243  204  7   Q1       A          53.52      44.93     1.54

I tried with dcast from reshape2 but its not working. Any help would be great

NinjaR
  • 621
  • 6
  • 22

1 Answers1

1

Using pivot_wider :

tidyr::pivot_wider(df, names_from = Answer, values_from = c(Perc, Freq))

# A tibble: 1 x 8
#  Number Question Perc_ Perc_Yes Perc_No Freq_ Freq_Yes Freq_No
#  <chr>  <chr>    <dbl>    <dbl>   <dbl> <int>    <int>   <int>
#1 Q1     A         1.54     53.5    44.9     7      243     204

and with dcast from data.table

library(data.table)
dcast(setDT(df), Number + Question ~ Answer, value.var = c('Perc', 'Freq'))

data

df <- structure(list(Answer = c("", "Yes", "No"), Freq = c(7L, 243L, 
204L), Number = c("Q1", "Q1", "Q1"), Question = c("A", "A", "A"
), Perc = c(1.54, 53.52, 44.93)), class = "data.frame", row.names = c(NA, -3L))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213