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

标签 r

识别每个 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/

相关文章:

r - 将复数值分配给R中数据帧的字符元素

r - 使用 apply 函数填充 NA 矩阵

r - R 中的实验设计 : balanced incomplete block design

r - 在环境中使用 UseMethod 进行方法分派(dispatch)

file - 如何格式化 CSV 文件中的数据,以便可以轻松地将其导入到 R 中?

R Shiny 加速数据加载

r - Plotly - 用 R 发布我的 plotly

r - 错误: Discard position id too big

r - 如何按组将 2 个函数添加到回归中?

r - 在R中简洁地创建一个区间变量