【问题标题】:Row mean and number of entries per row using data.table in R使用 R 中的 data.table 的行平均值和每行的条目数
【发布时间】:2019-10-21 10:20:49
【问题描述】:

我有一个包含 640 行和 50 列的数据框。

第 1 - 4 列有一些 ID 和字符变量,而 5 - 50 列有实际数据。对于每一行,第 5:50 列中的缺失值显示为 -9999。我想做两件事:

  • 对于每一行,我想计算第 5 - 50 列的行平均值
  • 计算未丢失的值的数量,即 != -9999 这就是我目前的做法
apply(temp[, 5:50], 1 , function(x) mean(x[x != -9999]))  # for mean
apply(temp[, 5:50], 1 , function(x) sum(x[x != -9999]))   # for number of values not equal to -9999

我现在正在学习data.table,所以想知道如何在 data.table 中实现相同的功能。我做到了:

temp[, .(Mean = rowMeans(.SD)), by = c('ID1','ID2','ID3','ID4')]

如何排除 -9999 并在不包括 -9999 的情况下计算每行的数据点数?

【问题讨论】:

  • 如果你做一个最小可重复的例子会很棒。
  • 我猜你的计数代码应该是:apply(temp[, 5:50], 1 , function(x) sum(x != -9999)) ?
  • @ismirsehregal 谢谢。我认为你是对的。我的代码有错误

标签: r data.table


【解决方案1】:

我建议将-9999 替换为NA,然后将na.rm = TRUE 替换为rowMeans

library(data.table)
temp <- data.table(replicate(4, rep("charVar", 640)), replicate(46, sample(c(0:100, -9999), 640, rep = TRUE)))

for (j in 5:50){set(temp, which(temp[[j]] == -9999), j, NA)}
temp[, .(Mean = rowMeans(.SD, na.rm = TRUE), Count = rowSums(!is.na(.SD))), .SDcols=c(5:50)]

# If you want to add the new columns to the existing data.table use:
# temp[, c("Mean", "Count") := .(rowMeans(.SD, na.rm = TRUE), rowSums(!is.na(.SD))), .SDcols=c(5:50)]

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 2020-03-07
    • 1970-01-01
    • 2017-10-04
    • 2014-08-09
    • 1970-01-01
    • 2019-07-26
    • 2023-03-21
    相关资源
    最近更新 更多