gpt4 book ai didi

r - 识别每个 ID 的第一列值并根据该值进行操作

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

识别每个 ID 的第一列值并根据该值替换

我有以下包含许多列的 df:

input <- data.frame(ID = c(1,1,1,1,1,2,2,3,3,3),
Obs1 = c(1,0,1,1,0,0,1,1,0,1),
Obs2 = c(0,1,1,0,1,1,1,1,1,0),
Control1 = c(1,1,2,2,2,1,2,1,1,2),
Control2 = c(1,2,2,2,3,1,1,1,2,2))

我想修改“控制”列的值。如果每个 ID 的第一个“Obs”值为 0,那么我必须将 -1 减去整个 ID 组:

result <- data.frame(ID = c(1,1,1,1,1,2,2,3,3,3),
Obs1 = c(1,0,1,1,0,0,1,1,0,1),
Obs2 = c(0,1,1,0,1,1,1,1,1,0),
Control1 = c(1,1,2,2,2,0,1,1,1,1),
Control2 = c(0,1,1,1,2,1,1,1,2,2))

我获取每个 ID 的第一个 obs 值的方式如下:

i <- 1 
aux <- vector("list", 2)

for (i in 2:3)
aux [[i]] <- input[!duplicated(input$ID), i]

使用此列表,如何修改“控制”列? (我有100多个)

最佳答案

使用 data.table,我会先将您的数据转换为长格式(同时使用 "Obs" 函数将所有 "Control"patterns 列合并为相同的列),进行计算并转换回宽格式。这将扩展到任意数量的对。

library(data.table)
library(magrittr)

# The patterns of the columns we will be working with
cols <- c("Obs", "Control")

res <-
# convert to data.table and add row index so we can dcast back afterwards
setDT(input)[, rowind := .I] %>%

# Convert to long format and combine all Obs and Controls into two columns
melt(., id = c("rowind", "ID"), patterns(cols), value.name = cols) %>%

# Reduce 1 from Control in case the first value is zero
.[, Control := Control - first(Obs == 0), by = .(ID, variable)] %>%

# Convert back to wide format
dcast(., ID + rowind ~ variable, value.var = cols, sep = "") %>%

# Remove the row index
.[, rowind := NULL]

res
# ID Obs1 Obs2 Control1 Control2
# 1: 1 1 0 1 0
# 2: 1 0 1 1 1
# 3: 1 1 1 2 1
# 4: 1 1 0 2 1
# 5: 1 0 1 2 2
# 6: 2 0 1 0 1
# 7: 2 1 1 1 1
# 8: 3 1 1 1 1
# 9: 3 0 1 1 2
# 10: 3 1 0 2 2

关于r - 识别每个 ID 的第一列值并根据该值进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51081423/

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