【问题标题】:Apply a function to variables with a name pattern for each id with NA values将函数应用于具有名称模式的变量,每个 id 具有 NA 值
【发布时间】:2015-03-30 19:35:03
【问题描述】:

我有一个数据表,我想在其中计算每个 id 的以“数量”开头的变量组的平均值。

以数量开头的变量数量可能会有所不同,但在我的真实数据中它们远远超过 100(并且一些变量具有 NA 值)。

id  variable    amountA amountB amountC amountD
1   A   8   7   6   2
2   B   6   2   1   2
3   C   6   6   9   4
4   D   1   6   2   7

在我的数据中我尝试过没有成功:

DT[,testvar := apply(DT[ ,grepl("amount",names(DT))],1,mean)]
DT[,testvar := mean(DT[ ,grepl("amount",names(DT))],na.rm=TRUE), by = idvar]

我正在尝试使用 .EACHI 解决它,但我还没有弄清楚。任何想法或评论都非常感谢。

示例表:

structure(list(id = 1:4, variable = structure(1:4, .Label = c("A", 
"B", "C", "D"), class = "factor"), amountA = c(8L, 6L, 6L, 1L
), amountB = c(7L, 2L, 6L, 6L), amountC = c(6L, 1L, 9L, 2L), 
    amountD = c(2L, 2L, 4L, 7L)), .Names = c("id", "variable", 
"amountA", "amountB", "amountC", "amountD"), class = "data.frame", row.names = c(NA, 
-4L))

【问题讨论】:

  • 检查HTML vignettes,尤其是Introduction to data.table 小插图中的.SD.SDcols 部分。

标签: r loops data.table


【解决方案1】:

以下是采用 Arun 的一些建议的可能解决方案:

DT[, testvar:=rowMeans(.SD, na.rm=T), .SDcols=grep("^amount", names(DT), value=T)]

生产:

   id variable amountA amountB amountC amountD testvar
1:  1        A       8       7       6       2    5.75
2:  2        B       6       2       1       2    2.75
3:  3        C       6       6       9       4    6.25
4:  4        D       1       6       2       7    4.00

我们使用.SDcolsgrep 定义我们希望哪些列成为内部.SD 对象的一部分,然后我们只需rowSums 生成.SD

data.table 的更新版本中,您可以通过在.SDcols 中使用patterns 来快捷方式:

DT[, testvar := rowMeans(.SD, na.rm = TRUE), .SDcols = patterns('amount')]

【讨论】:

  • @Arun,很好,虽然在这种情况下我们不知道“amountXX”的范围。你们添加了这么多功能,我觉得我在 DT 最前沿的东西上已经无可救药地过时了。
  • @Arun,OP 声明 AmountX 变量的数量“可能会有所不同,但在我的真实数据中它们远远超过 100”
  • @Arun,我想问你是否在工作类似rowwise,但后来我想我应该检查一下。我意识到强制和结果副本,但不想在这个答案中深入研究。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-23
  • 2021-08-03
  • 1970-01-01
  • 2011-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多