繁体   English   中英

R - 对数据集进行分类

[英]R - Categorize a dataset

各位早上好

我正在尝试对一组数值进行分类(剩余天数除以 365.2,这给出了大约到期前剩余的年数)。

第一次计算的结果为我提供了一个包含 3560 个值的向量(示例:0.81、1.65、3.26 [...]、0.2)。

我想将这些结果分类为区间,[0 到 1 年之间,0 到 2 年之间,0 到 3 年之间,0 到 4 年之间,4 年以上]。

#Set the Data Frame
dfMaturity <- data.frame(Maturity = DATA$Maturity)

#Call the library and Run the function
MaturityX = ddply(df, .(Maturity), nrow)

#Set the Data Frame
dfMaturityID <- data.frame(testttto = DATA$Security.Name)

#Calculation of the remaining days
MaturityID = ddply(df, .(dfMaturityID$testttto), nrow)

survey <- data.frame(date=c(DATA$Maturity),tx_start=c("1/1/2022"))

survey$date_diff <- as.Date(as.character(survey$date), format="%m/%d/%Y")-
  as.Date(as.character(survey$tx_start), format="%m/%d/%Y")

# Data for the table
MaturityName <- MaturityID$`dfMaturityID$testttto
MaturityZ <- survey$date
TimeToMaturity <- as.numeric(survey$date_diff)

# /!/ HERE IS WHERE I NEED HELP /!/ I'M TRYING TO CATEGORISE THE RESULTS OF THIS CALCULATION
Multiplier <- TimeToMaturity /365.2
cx <- cut(Multiplier, breaks=0:5)

原始数据源来自一个 excel 文件 (DATA$Maturity)

如果对你有帮助:

''' 打印(乘数)'''

给我们

print(Multiplier)
   [1]  0.4956188  1.4950712  1.9989047  0.2464403  0.9994524  3.0010953  5.0000000  7.0016429  9.0005476
  [10] 21.0021906  4.1621030 13.1626506  1.1610077  8.6664841 28.5377875  3.1626506  6.7497262  2.0920044
  [19]  2.5602410  4.6495071  0.3368018  6.3225630  8.7130340 10.4956188  3.9019715 12.7957284  5.8378970

我复制了前三行,但总共有 3560 个对象。

我愿意接受任何形式的帮助,我只希望它能正常工作:) 谢谢!

cut function 这样做:

example <- c(0.81, 1.65, 3.26, 0.2)

cut(example, breaks = c(0, 1, 2, 3, 4), 
    labels = c("newborn", "one year old", "two", "three"))

编辑:来自评论

然后我想创建一个表,例如:30% 的对象的成熟度在 0 到 1 年之间

您可以使用下面的 function 来计算:

example <- c(0.81, 1.65, 3.26, 0.2)

share <- function(x, lower = 0, higher= 1){
  x <- na.omit(x)
  sum((lower <= x) & (x < higher))/length(x)
}

share(1:10, lower = 0,higher = 3.5) # true for 1:3 out of 1:10 so 30%

share(1:10, lower = 4.5, higher = 5.5) # true for 5 so 10%)

share(example, 0, 3)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM