【问题标题】:Splitting data based on the ranges in R根据 R 中的范围拆分数据
【发布时间】:2016-04-06 00:03:20
【问题描述】:

我想知道如何将主题划分为 4 个不同的范围/级别。每个级别都有一定的范围。以下是数据。

Std   Name   Subject  Percentage
   2   Vinay   eng      50
   2   Vinay   math     60
   2   Vinay   hindi    70
   2   Rohan   eng      70
   2   vas     mat      50
   2   dheer   eng      35
   2   dheer   math     90
   2   dheer   hindi    80
   2   Bhas    eng      90
   2   Bhas    math     35
   2   Bhas    hindi    50

四个桶范围如下。 75

预期输出:

Std Subject 0-35  35-50  50-75  >75
2    Eng     25%  25%    25%   25%
2    Mat     25%  25%    25%   25%
2    Hin     0%   25%    25%   25%

P.s 范围的值是在该范围内得分的学生的百分比。

提前致谢

【问题讨论】:

  • 最好有一个代码来重现所使用的数据。
  • @M.D 数据本身是原始数据。

标签: r sqldf


【解决方案1】:

可能的 data.table 解决方案:

library(data.table)

dat <- data.table(Std = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L),
                  Name = c("Vinay", "Vinay", "Vinay", "Rohan", "vas", "dheer", "dheer", "dheer", "Bhas", "Bhas", "Bhas"),
                  Subject = c("eng", "math", "hindi", "eng", "mat", "eng", "math", "hindi", "eng", "math", "hindi"),
                  Percentage = c(50L, 60L, 70L, 70L, 50L, 35L, 90L, 80L, 90L, 35L, 50L))

dat[, PCTs := cut(Percentage,
                  breaks = c(0, 35, 50, 75, 100),
                  include.lowest = TRUE)]

res <- dat[, list(
               "0-35" = sum(PCTs == "[0,35]") / .N * 100,
               "35-50" = sum(PCTs == "(35,50]") / .N * 100,
               "50-75" = sum(PCTs == "(50,75]") / .N * 100,
               ">75" = sum(PCTs == "(75,100]") / .N * 100
             ),
             by = c("Std", "Subject")]

print(res, digits = 2)

【讨论】:

  • 感谢您的解决方案,但是如果我有 500 条这样的记录,很难在 data.table 中硬编码,可以选择导入文件,尝试使用 dat
  • 上面的代码假设使用了data.table,所以要么使用as.data.table(yourObject),要么使用data.table包中的fread()函数。
  • 太棒了! data.table 语法乍一看可能有点奇怪,但不要害怕!
  • 从上面的代码中它还包括范围内的 35,50,75,100,我尝试使用 [0,35), [35,50), [50,75), [75,100] 但它显示为 0
  • 使用"[0,35]""(35,50]" 等,您只需选择特定的PCTs 值,以更改您想要包含哪些端点以及排除cut() 函数的检查选项,即使用@ R 控制台中的 987654331@。
【解决方案2】:

这应该可以工作,可能需要更多的格式化工作:

df<-read.table(header = TRUE, sep=",", text="Std,   Name,   Subject,  Percentage
              2,   Vinay,eng,     50
               2,   Vinay,math,     60
               2,   Vinay,hindi,    70
               2,   Rohan,eng,      70
               2,   vas,math,      50
               2,   dheer,eng,      35
               2,   dheer,math,    90
               2,   dheer,hindi,    80
               2,   Bhas,eng,     90
               2,   Bhas,math,     35
               2,   Bhas,hindi,    50")

breaks<-c(0, 35, 50, 75, 100)
t<-table(df$Subject, responseName=cut(df$Percentage, breaks = breaks) )
format(t/rowSums(t), digits=3)

【讨论】:

  • 感谢您的回复,因为 std 在它显示分组依据的所有记录中都是相同的,如果标准不同,在代码中的何处包含 by 子句怎么办?
猜你喜欢
  • 2014-09-02
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
  • 2022-11-18
  • 2021-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多