首页 > 解决方案 > 有没有办法将特定数量的列转换为 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

我的问题现在更清楚了吗?如果我应该添加一些东西,请告诉我。对不起,我对此完全陌生。

标签: rdplyr

解决方案


这可能不是最有效的方法,但它确实有效。

注意:您的“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

推荐阅读