r - How to group by on all the columns in data.frame?
问题描述
I have following data.frame
in R:
Introvert Extrovert Nature Presence
0 -1 3 Yes
1 3 2 No
2 5 4 Yes
1 -2 0 No
Now, I want to code the responses in following manner:
3,4 <- Positives
0,1,2 <- Neutral
< 0 <- Negatives
And then get the count of Positives
, Negatives
and Neutrals
across Yes
and No
.
I have 20 columns of responses like the above. How can I do it in simpler code in R?
I am doing it ifelse
and then group_by
for every column.
My sample desired dataframe would be:
Introvert_Positive Introvert_Negative Introvert_Neutral
Yes 0 0 2
No 0 0 2
解决方案
这个怎么样?
library(tidyverse);
df %>%
gather(key, value, -Presence) %>%
mutate(bin = cut(
value,
breaks = c(-Inf, -1, 2.5, Inf),
labels = c("Negatives", "Neutral", "Positives"))) %>%
select(-value) %>%
unite(col, key, bin, sep = "_") %>%
count(Presence, col) %>%
spread(col, n)
## A tibble: 2 x 6
# Presence Extrovert_Negativ… Extrovert_Positi… Introvert_Neutr… Nature_Neutral
# <fct> <int> <int> <int> <int>
#1 No 1 1 2 2
#2 Yes 1 1 2 NA
## ... with 1 more variable: Nature_Positives <int>
解释:我们使用cut
withlabels
重新编码响应;剩下的就是gather
ing、unite
ing 相关列、count
ing 出现次数以及spread
ing 从长到宽。
样本数据
df <- read.table(text =
"Introvert Extrovert Nature Presence
0 -1 3 Yes
1 3 2 No
2 5 4 Yes
1 -2 0 No", header = T)
推荐阅读
- rest - 我对 Roy Fielding 的 REST 替代 HTTP cookie 的解释是否正确?
- android - Android 模拟器上的未知错误,在运行 android studio 的 Amazon Ec2 Windows 服务器上
- nginx - 无法访问此站点 puma,nginx rails deploy
- javascript - 如何防止每次父组件渲染时都渲染反应组件?
- javascript - Webassembly:可能有共享对象吗?
- python-3.x - 从网站上抓取视频并将其下载为 mp4
- excel - 如何从一张纸一次复制一行数据并粘贴到另一张纸上
- php - 连接失败 - 使用 php 7.3 和 8.0 失败 - 尝试 wamp 和 xampp - 尝试访问 sqlserver 数据库
- uitextfield - Mac Catalyst - 无法覆盖 UITextField 中的突出显示颜色
- python - 使用 VGG Keras 更改锚点以增加区域提案网络 (RPN) 的 IOU