Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i convert factor only column of Likert scale from long to wide using dplyr functions in R?

i have the following data frame in R with 3 factor column with the same levels like this :

A B C
1 1-Strongly disagree 5-Strongly agree 1-Strongly disagree
2 3-so-so 5-Strongly agree 2-Disagree
3 4-Agree 2-Disagree 2-Disagree
4 2-Disagree 2-Disagree 5-Strongly agree

and i want to use dplyr functions in order to alter my data frame into like this :

Item 1-Strongly disagree 2-Disagree 3-so-so 4-Agree 5-Strongly agree
A 26.72 21.41 27.45 17.80 6.59
B 25.0 20.2 28.27 18.36 8.0
C 6.3 9.5 28.6 40.35 15.17

where the numbers on the cells are arbitrary.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A = sample(c('1-Strongly disagree','2-Disagree','3-so-so','4-Agree','5-Strongly agree'),1000,replace = TRUE)
B = sample(c('1-Strongly disagree','2-Disagree','3-so-so','4-Agree','5-Strongly agree'),1000,replace = TRUE)
C = sample(c('1-Strongly disagree','2-Disagree','3-so-so','4-Agree','5-Strongly agree'),1000,replace = TRUE)

df = tibble(A,B,C)%>%
  mutate(across(everything(),as.factor));df

>Solution :

library(tidyverse)
set.seed(1234) # for reproducible testing
A = sample(c('1-Strongly disagree','2-Disagree','3-so-so','4-Agree','5-Strongly agree'),1000,replace = TRUE)
B = sample(c('1-Strongly disagree','2-Disagree','3-so-so','4-Agree','5-Strongly agree'),1000,replace = TRUE)
C = sample(c('1-Strongly disagree','2-Disagree','3-so-so','4-Agree','5-Strongly agree'),1000,replace = TRUE)

df = tibble(A,B,C)%>%
  mutate(across(everything(),as.factor));df

df |> 
  pivot_longer(cols = everything(), names_to = "Item") |>
  pivot_wider(names_from = value, values_fn = length)

gives

# A tibble: 3 × 6
  Item  `4-Agree` `1-Strongly disagree` `2-Disagree` `5-Strongly agree` `3-so-so`
  <chr>     <int>                 <int>        <int>              <int>     <int>
1 A           194                   194          181                197       234
2 B           193                   195          194                219       199
3 C           201                   195          205                199       200
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading