首页 > 解决方案 > R检查多个条件并从列转换为行

问题描述

我有下表:

ID 行动 乐趣 历史 用处 意图
一种 4 5 1 非常同意 同意
b 5 3  4 同意 同意
C 3 3 4 同意 不同意
d 4 3 5 中性的 同意
e 1 3 4 同意 同意

现在我想成为动作的每一行,fun或者history是高于 3 的单行。这意味着如果或都在 3 以上action,它应该是三行。带有 ID 的条目应该是两行(并且在 3 以上,在 3 以下),如下所示:funhistoryaactionfunhistory

ID 类型 用处 意图
一种 行动 非常同意 同意
一种 乐趣 非常同意 同意
b 乐趣   同意 同意
b 历史 同意 同意
C 历史 同意 不同意

最后我想有一个这样的李克特情节: 示例图

type作为汽车品牌和两组(usefulnessintention)。

标签: rdplyr

解决方案


混合tidyr溶液;

library(tidyr)
library(dplyr)


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

输出;

  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    

数据;

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
))

推荐阅读