gpt4 book ai didi

r - 如何使用长格式的 R 数据帧的子集进行操作?

转载 作者:行者123 更新时间:2023-12-04 16:54:10 25 4
gpt4 key购买 nike

我有一个包含 3 个组和 3 天的数据框:

set.seed(10)
dat <- data.frame(group=rep(c("g1","g2","g3"),each=3), day=rep(c(0,2,4),3), value=runif(9))
# group day value
# 1 g1 0 0.507478
# 2 g1 2 0.306769
# 3 g1 4 0.426908
# 4 g2 0 0.693102
# 5 g2 2 0.085136
# 6 g2 4 0.225437
# 7 g3 0 0.274531
# 8 g3 2 0.272305
# 9 g3 4 0.615829

我想取 log2 并将每个值除以每组中的第 0 天值。我现在的做法是在中间步骤中计算每个日组:
day_0 <- dat[dat$day==0, "value"]
day_2 <- dat[dat$day==2, "value"]
day_4 <- dat[dat$day==4, "value"]
res <- cbind(0, log2(day_2/day_0), log2(day_4/day_0))
rownames(res) <- c("g1","g2","g3")
colnames(res) <- c("day_0","log_ratio_day_2_day_0","log_ratio_day_4_day_0")
# day_0 log_ratio_day_2_day_0 log_ratio_day_4_day_0
# g1 0 -0.7261955 -0.249422
# g2 0 -3.0252272 -1.620346
# g3 0 -0.0117427 1.165564

正确的计算方式是什么 res没有中间步骤?

最佳答案

一个 data.table编码优雅和内存效率的解决方案

library(data.table)

DT <- data.table(dat)

# assign within DT by reference

DT[, new_value := log2(value / value[day == 0]), by = group]
或者你可以使用 joinskeysby-without-by
DTb <- data.table(dat)

setkey(DTb, group)

# val0 contains just those records for day 0
val0 <- DTb[day==0]

# the i.value refers to value from the i argument
# which is in this case `val0` and thus the value for
# day = 0
DTb[val0, value := log2(value / i.value)]
这两种解决方案都不需要您按 day 排序确保 value将第一个(或任何特定的)元素。

编辑
文档为 i.句法
    **********************************************
** **
** CHANGES IN DATA.TABLE VERSION 1.7.10 **
** **
**********************************************
NEW FEATURES

o New function setcolorder() reorders the columns by name
or by number, by reference with no copy. This is (almost)
infinitely faster than DT[,neworder,with=FALSE].

o The prefix i. can now be used in j to refer to join inherited
columns of i that are otherwise masked by columns in x with
the same name.

关于r - 如何使用长格式的 R 数据帧的子集进行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13220395/

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