gpt4 book ai didi

r - 从 R 列中的引用值中查找类别

转载 作者:行者123 更新时间:2023-12-01 08:10:31 29 4
gpt4 key购买 nike

我有以下数据和代码:

> dput(mydata)
structure(list(P3 = c(99.4, 105.8, 111.9), P5 = c(100.4, 106.9,
113.1), P10 = c(102, 108.6, 114.9), P25 = c(104.8, 111.6, 118.1
), P50 = c(108, 115, 121.8), P75 = c(111.2, 118.6, 125.6), P90 = c(114.3,
121.9, 129.1), P95 = c(116.1, 123.9, 131.3), P97 = c(117.4, 125.3,
132.7), val = c(115.5, 112.7, 117)), .Names = c("P3", "P5", "P10",
"P25", "P50", "P75", "P90", "P95", "P97", "val"), row.names = 7:9, class = "data.frame")
>
> mydata
P3 P5 P10 P25 P50 P75 P90 P95 P97 val
7 99.4 100.4 102.0 104.8 108.0 111.2 114.3 116.1 117.4 115.5
8 105.8 106.9 108.6 111.6 115.0 118.6 121.9 123.9 125.3 112.7
9 111.9 113.1 114.9 118.1 121.8 125.6 129.1 131.3 132.7 117.0

我想在 mydata 中创建一个新列“categ”,其中第一列名称的“数字”部分(从左到右检查)包含的值大于该行的“val”。

因此,我应该在新列中得到 95,50,25。

我知道用于此类分类的“findInterval”和“match”函数,但我无法将它们应用于 mydata。感谢您的帮助。

最佳答案

你可以试试

indx <- max.col(mydata[,-10] >mydata$val,'first')
mydata$categ <- as.numeric(sub("[A-Z]+", "", names(mydata)[indx]))
mydata$categ
#[1] 95 50 25

或者

indx <- apply(mydata[,-10] > mydata$val, 1, function(x) names(which(x))[1])

然后像以前一样使用sub

数据

mydata <- structure(list(P3 = c(99.4, 105.8, 111.9), P5 = c(100.4, 106.9, 
113.1), P10 = c(102, 108.6, 114.9), P25 = c(104.8, 111.6, 118.1
), P50 = c(108, 115, 121.8), P75 = c(111.2, 118.6, 125.6), P90 = c(114.3,
121.9, 129.1), P95 = c(116.1, 123.9, 131.3), P97 = c(117.4, 125.3,
132.7), val = c(115.5, 112.7, 117)), .Names = c("P3", "P5", "P10",
"P25", "P50", "P75", "P90", "P95", "P97", "val"), class = "data.frame",
row.names = c("7", "8", "9"))

关于r - 从 R 列中的引用值中查找类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27588528/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com