r - 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 以下),如下所示:fun
history
a
action
fun
history
ID | 类型 | 用处 | 意图 |
---|---|---|---|
一种 | 行动 | 非常同意 | 同意 |
一种 | 乐趣 | 非常同意 | 同意 |
b | 乐趣 | 同意 | 同意 |
b | 历史 | 同意 | 同意 |
C | 历史 | 同意 | 不同意 |
最后我想有一个这样的李克特情节:
与type
作为汽车品牌和两组(usefulness
,intention
)。
解决方案
混合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
))
推荐阅读
- javascript - 如何获取最后两个 URL 段?
- reactjs - 在控制台中正确返回数据之前,我需要单击两次
- javascript - 给定一个表示非负整数的非空数字数组,将整数加一(javascript)
- angular - 如何通过Angular中的url更改动态更改类
- go - 为什么 Golang 像这样在 atoi.go 中处理截止?
- vuejs2 - 我们可以在 element-ui 下拉列表的命令属性中传递 vue 数据对象吗?
- nlp - QA问题系统中多个正确答案的评价指标
- python - 如何构造一个将类似元组的参数作为输入传递的函数?
- python - 读取和写入 csv 到同一位置时,Pyspark 文件被删除
- scala - 一个“简单”的 Scala 问题,但我花了很长时间来调试