【问题标题】:R data.frame matching across columns and returning the column name of closest matchR data.frame 跨列匹配并返回最接近匹配的列名
【发布时间】:2014-10-15 21:54:38
【问题描述】:

我有一个包含 100,000 行(人)和 500 列(概率)的数据集,我想扫描具有测试概率的列以找到大于和的列标题(a、b 或 c)最接近测试值并将标题记录在新列中。

例如使用 data.table:

data <- data.table(   a = seq(0.2, 0.55, length.out = 9),
                      b = seq(0.35, 0.7, length.out = 9),
                      c = seq(0.5, 0.85, length.out = 9),
                   test = seq(0.1,  0.9, length.out = 9)
                  )

新列将记录第一行的“a”(如 0.1

       a    b   c   test
 0.20000    0.35000 0.50000 0.1
 0.24375    0.39375 0.54375 0.2
 0.28750    0.43750 0.58750 0.3
 0.33125    0.48125 0.63125 0.4
 0.37500    0.52500 0.67500 0.5
 0.41875    0.56875 0.71875 0.6
 0.46250    0.61250 0.76250 0.7
 0.50625    0.65625 0.80625 0.8
 0.55000    0.70000 0.85000 0.9

我最初将其作为矩阵而不是 data.table 进行。下面的代码不起作用,但可以了解它是如何操作的

Switch <- pmax(as.matrix(data[,a:c])-matrix(rep(test,3), ncol=3, byrow=F),0)  
# subtracts test from columns a,b,c and replaces negative values with 0

FirstSwitch <- Switch[,b:c]>0 & MemSwitch[,a:b]==0
#  finds the first non-zero occurance

MonthSwitchMem <-  apply(FirstSwitch, 1, which.max)
# calculates the column where the test probability first exceeds

如何跨 data.table 中的列进行匹配。我想我需要使用来自 .SDcols 的查询,但不知道该怎么做?

【问题讨论】:

    标签: r match data.table


    【解决方案1】:

    我调整了 Karolis 的答案,因此我将我的列从 data.table 转移到提供的 sn-p

    data <- data.frame(   a = seq(0.2, 0.55, length.out = 9),
                      b = seq(0.35, 0.7, length.out = 9),
                      c = seq(0.5, 0.85, length.out = 9),
                      test = seq(0.1,  0.9, length.out = 9)
    )
    data2 <- data.table(data)
    id <- c("a","b","c")
    f <- function(x, t) {colnames(data2)[apply(sign(x-t), 1,function(vec){ match(1, vec) })]}
    data2[, f(.SD, data2[,test]),.SDcols=id ]  #  this line takes the columns with the probabilities and the test probability and transfer to function f
    

    感谢您的帮助(并重新格式化我的问题。这是我的第一篇文章,因此为错误的格式道歉)

    普拉尚特

    【讨论】:

      【解决方案2】:

      这适用于作为矩阵的数据(不是 data.table)。

      colnames(data)[apply(sign(data[,1:3] - data[,4]), 1, function(vec){ match(1, vec) })]
      

      【讨论】:

      • 嗨卡罗利斯非常感谢这个想法和问题的编辑。它适用于 data.frame。我试图转换为 data.table 但到目前为止没有成功。我的翻译尝试不起作用: data2 f data2[, apply(.SD, 1,f, data2[,test]),.SDcols=id ]
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多