Home > front end >  R check for multiple conditions and transform from column to row
R check for multiple conditions and transform from column to row

Time:10-24

I have the following table:

id action fun history usefulness intention
a 4 5 1 Strongly Agree Agree
b 5 3  4 Agree Agree
c 3 3 4 Agree Disagree
d 4 3 5 Neutral Agree
e 1 3 4 Agree Agree

Now I want to be every row where action, fun or history is above 3 to be a single row. It means that if action, fun or history are all above 3, it should be three rows. The entry with ID a should be two rows (action and fun above 3, history below 3) and look like below:

id type usefulness intention
a action Strongly Agree Agree
a fun Strongly Agree Agree
b fun   Agree Agree
b history Agree Agree
c history Agree Disagree

In the end I would like to have a likert plot like this: Example Plot

With type as car brands and two groups (usefulness, intention).

CodePudding user response:

a tidyr mixed solution;

library(tidyr)
library(dplyr)


df %>%
  pivot_longer(cols = c("action", "fun", "history"), names_to = "type") %>%
  filter(value > 3) %>%
  select(-value) %>%
  relocate(type, .after = id)

output;

  id    type    usefulness     intention
  <chr> <chr>   <chr>          <chr>    
1 a     action  Strongly Agree Agree    
2 a     fun     Strongly Agree Agree    
3 b     action  Agree          Agree    
4 b     history Agree          Agree    
5 c     history Agree          Disagree 
6 d     action  Neutral        Agree    
7 d     history Neutral        Agree    
8 e     history Agree          Agree    

data;

df <- structure(list(id = c("a", "b", "c", "d", "e"), action = c(4L, 
5L, 3L, 4L, 1L), fun = c(5L, 3L, 3L, 3L, 3L), history = c(1L, 
4L, 4L, 5L, 4L), usefulness = c("Strongly Agree", "Agree", "Agree", 
"Neutral", "Agree"), intention = c("Agree", "Agree", "Disagree", 
"Agree", "Agree")), class = "data.frame", row.names = c(NA, -5L
))
  • Related