gpt4 book ai didi

r - data.frame 中的行数相等

转载 作者:行者123 更新时间:2023-12-01 12:50:09 25 4
gpt4 key购买 nike

我有一个如下所示的数据框:

df <- data.frame(
Logical = c(TRUE,FALSE,FALSE,FALSE,FALSE,FALSE),
A = c(1,2,3,2,3,1),
B = c(1,0.05,0.80,0.05,0.80,1),
C = c(1,10.80,15,10.80,15,1))

看起来像:

  Logical A    B    C
1 TRUE 1 1.00 1.0
2 FALSE 2 0.05 10.8
3 FALSE 3 0.80 15.0
4 FALSE 2 0.05 10.8
5 FALSE 3 0.80 15.0
6 FALSE 1 1.00 1.0

我想添加一个新变量 D,它是一个基于以下规则的整数:0 if df$LogicalTRUE,或者对于变量 ABC 的所有行都相同的整数从 1 开始大致相等(因为它们是 double ,所以在浮点误差范围内)。

这里的预期输出:

  Logical A    B    C D
1 TRUE 1 1.00 1.0 0
2 FALSE 2 0.05 10.8 1
3 FALSE 3 0.80 15.0 2
4 FALSE 2 0.05 10.8 1
5 FALSE 3 0.80 15.0 2
6 FALSE 1 1.00 1.0 3

第一行得到 0 因为 LogicalTRUE,第二和第四行得到 1 因为变量 A, BC 大致相等,第二行和第五行也一样。第六行获得 3,因为它是下一个唯一行。请注意,D 中分配的整数顺序无关紧要,0 除外。例如,第 2 行和第 4 行也可以分配 2,只要该整数在 D 的其他情况下是唯一的即可。


我考虑过使用聚合函数。例如使用 ddply:

library("plyr")
df$foo <- 1:nrow(df)
foo <- dlply(df,.(A,B,C),'[[',"foo")
df$D <- 0
for (i in 1:length(foo)) df$D[foo[[i]]] <- i
df$D[df$Logical] <- 0

有效,但我不确定这对浮点错误的处理效果如何(我想我可以在调用之前将此处的值四舍五入,但它应该非常稳定)。使用循环很容易:

df$D <- 0
c <- 1
for (i in 1:nrow(df))
{
if (!isTRUE(df$Logical[i]) & df$D[i]==0)
{
par <- sapply(1:nrow(df),function(j)!df$Logical[j]&isTRUE(all.equal(unlist(df[j,c("A" ,"B", "C")]),unlist(df[i,c("A" ,"B", "C")]))))
df$D[par] <- c
c <- c+1
}
}

但这对于较大的数据帧来说非常慢。

最佳答案

根据下面 Matthew Dowle 的评论,data.table 可以对数值进行分组,并使用 .Machine$double.eps^.5 容差来区分它们。考虑到这一点,data.table 解决方案应该可行:

library(data.table)

DT <- as.data.table(df)

DT[, D := 0]

.GRP <- 0

DT[!Logical, D := .GRP <- .GRP + 1, by = "A,B,C"]

# Logical A B C foo D
# 1: TRUE 1 1.00 1.0 1 0
# 2: FALSE 2 0.05 10.8 2 1
# 3: FALSE 3 0.80 15.0 3 2
# 4: FALSE 2 0.05 10.8 4 1
# 5: FALSE 3 0.80 15.0 5 2
# 6: FALSE 1 1.00 1.0 6 3

正如 Matthew Dowle 所写 here , .GRP 是在data.table 1.8.3实现的,但我还是1.8.2


根据评论跟进,这是 1.8.2 的新闻项目。将添加到 ?data.table,感谢您的突出显示!

Numeric columns (type double) are now allowed in keys and ad hoc by. J() and SJ() no longer coerce double to integer. i join columns which mismatch on numeric type are coerced silently to match the type of x's join column. Two floating point values are considered equal (by grouping and binary search joins) if their difference is within sqrt(.Machine$double.eps), by default. See example in ?unique.data.table. Completes FRs #951, #1609 and #1075. This paves the way for other atomic types which use double (such as POSIXct and bit64). Thanks to Chris Neff for beta testing and finding problems with keys of two numeric columns (bug #2004), fixed and tests added.

关于r - data.frame 中的行数相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13067849/

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