【问题标题】:substract subset of data frame from the same data frame从同一数据帧中减去数据帧的子集
【发布时间】:2016-07-19 11:53:32
【问题描述】:

我有一个如下结构的数据框: 它可以有多个行和列

v<-c("control", NA, 1, 2, 4, "test", NA, 1, 2, 4, "test", NA, 1, 2, 4, "test", NA, 1, 2, 4)
df<- as.data.frame(t(matrix(v, nrow=5, ncol=4)))
colnames(df)<-c("ID", "G1", "G2", "G3", "G4")
df
       ID   G1 G2 G3 G4
1 control <NA>  1  2  4
2    test <NA>  1  2  4
3    test <NA>  1  2  4
4    test <NA>  1  2  4

我想从其他行中减去 ID==control 的行,得到以下结果:

result
           ID   G1 G2 G3 G4
    1    test <NA>  0  0  0
    2    test <NA>  0  0  0
    3    test <NA>  0  0  0

我尝试了 sweep() 函数,我尝试将它通过 for 循环,但没有任何效果。

如果有人可以帮助我,那就太棒了。 谢谢!

【问题讨论】:

  • 如果有两行 control 怎么办?
  • 你的列是因素
  • 到目前为止,我尽量避免使用 control 的 2 行,因为这会使后续统计数据更加复杂

标签: r dataframe subset


【解决方案1】:

假设只有一个“控件”,根据“控件”值(“i1”)创建一个逻辑索引,将“id”的“df”子集,而不是“控件”(“df1” ),使用Map从“ID”为“控制”的相同列中减去“df1”中的列,并将输出分配给“df1”中的相应列。

i1 <- df$ID=="control"
df1 <- df[!i1,]
df1[3:5] <- Map(`-`, df1[3:5], df[i1,3:5])
df1
#    ID   G1 G2 G3 G4
#2 test <NA>  0  0  0
#3 test <NA>  0  0  0
#4 test <NA>  0  0  0

或者不使用Map,我们可以复制以使两个数据集的长度相等并进行减法

df1[3:5] <- df1[3:5] - df[i1, 3:5][col(df1[3:5])]

数据

df[-(1:2)] <- lapply(df[-(1:2)], function(x) as.numeric(as.character(x)))

【讨论】:

  • 顺便说一句,你怎么知道谁被否决了你的答案?
  • @m0h3n 我不知道,但Map 是一个有效的答案
  • 感谢您的回答。不幸的是,我收到警告消息:Warning messages: 1: In Ops.factor(dots[[1L]][[3L]], dots[[2L]][[3L]]) : ‘-’ not meaningful for factors 2: In Ops.factor(dots[[1L]][[3L]], dots[[2L]][[3L]]) : ‘-’ not meaningful for factors 3: In Ops.factor(dots[[1L]][[3L]], dots[[2L]][[3L]]) : ‘-’ not meaningful for factors 导致 NA 是减法的结果
  • @KevinRoth 如果您查看“数据”下的代码,我已经将其更改为数字。
  • +1。我也很想知道你的回答HERE
【解决方案2】:

嗯,你可以用sweep点赞

sweep(df[!df$ID == "control", ][3:5],2,
                         as.numeric(as.vector(df[df$ID == "control", ][3:5])))


#   G2 G3 G4
#2   0  0  0
#3   0  0  0
#4   0  0  0

假设只有一行IDcontrol。您可以将没有ID 的行子集为control,并用ID 作为控制的行减去它。 as.numeric(as.vector(df[df$ID == "control", ][3:5])) 将其转换为要减去的向量。

【讨论】:

    猜你喜欢
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 2018-07-29
    • 1970-01-01
    相关资源
    最近更新 更多