Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205423

R- melting groups of columns from survey data -understanding how R(gather) works

$
0
0

New to code in general and have been through hundreds of google searches and stackoverflow threads but nothing yet really explains how my solution works. There are many ways to melt data, most appear overly complex...curious why my solution works when all other solutions are overly complex.

Original dataframe

> df <- data.frame(
ResponseID = c("123", "1234"),
Q1_W1 = c("Agree", "strongly disagree"),
Q1_W2 = c("disagree", "Agree"),
Q2_W1 = c("Disagree", "Disagree"),
Q2_W2 = c("Agree", "NA")
)

Desired output

  ResponseID variable value    variable     value
    123       Q1_W1   agree      Q2_W1      disagree     
   1234       Q1_W2   disagree   Q2_W2      agree      

I was able to achieve this with:

nalh5=ALH %>% gather(question,response, Q1_W1:Q1_W7)%>%
 gather(q2, r2,Q2_W1:Q2_W3)%>%
 gather(q3, r3, Q3_W1:Q3_W5)

It works well, but are there more efficient ways to achieve this?


Viewing all articles
Browse latest Browse all 205423

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>