r - 有没有办法将特定数量的列转换为 R 中的行?
问题描述
一种 | 乙 | C | n | % |
---|---|---|---|---|
错误的 | 错误的 | 错误的 | 随机数1 | 0.86 |
错误的 | 错误的 | 真的 | 随机数2 | 0.6 |
错误的 | 真的 | 错误的 | 随机数3 | 0.3 |
真的 | 错误的 | 错误的 | 随机数4 | 0.84 |
但我希望它看起来像这样:
姓名 | n | % |
---|---|---|
--- | 随机数1 | 0.86 |
C | 随机数2 | 0.6 |
乙 | 随机数3 | 0.3 |
一种 | 随机数4 | 0.84 |
我正在使用 R,但我对它很陌生,我在网上找不到任何解决方案。任何人都可以提出一种重组它们的方法吗?
我从谷歌表中得到数据,我想分析它。这就是我想出的:
re_eval<-datasheet %>%
filter(a_column_from_the_sheet_with_a_value == 1)%>%
count(endsWith(other_colum_with_string, "A"),
endsWith(other_colum_with_string, "B"),
endsWith(other_colum_with_string, "C"))%>%
mutate(accuracy = round(n/reg_collection[1:4,4],3)) #this line is not important
我的问题现在更清楚了吗?如果我应该添加一些东西,请告诉我。对不起,我对此完全陌生。
解决方案
这可能不是最有效的方法,但它确实有效。
注意:您的“n%”列没有正确的 R 列名称,所以我选择了“n_pct”。
df <- data.frame(A = c(F, F, F, T),
B = c(F, F, T, F),
C = c(F, T, F, F),
n = c(1, 2, 3, 4),
n_pct = c(0.86, 0.6, 0.3, 0.84))
library(tidyverse)
df %>%
pivot_longer(cols = c(A, B, C)) %>%
group_by(n) %>%
mutate(sum_value = sum(value),
name = if_else(sum_value == 0, "---", name),
helper = 1:n()) %>%
ungroup() %>%
filter(value == TRUE | (sum_value == 0 & helper == 1)) %>%
select(name, n, n_pct)
这使:
# A tibble: 4 x 3
name n n_pct
<chr> <dbl> <dbl>
1 --- 1 0.86
2 C 2 0.6
3 B 3 0.3
4 A 4 0.84
推荐阅读
- reactjs - @material-ui/pickers 已“成功”安装,但在启动开发服务器时“无法编译”
- java - 从 OpenCV 中的 Mat 对象填充二维数组时出现 NullPointerException
- windows - Powershell 脚本在第一次执行时不运行
- go - 如何使用 delve 调试器单步执行可执行文件?
- c# - 如何在另一个移动瓷砖的末端实例化一个瓷砖?
- express - 在 heroku 上使用 express 和 webpack 配置运行 prod 服务器
- spring - Spring MVC:将请求参数绑定到通用列表
- python - 循环遍历数据框列表以动态创建新列
- python-3.x - Django 静态文件保存在意外位置
- php - 以编程方式将 Woocommerce 购物车项目从虚拟更改为物理