r - 使用 R 的应用函数之一简化代码

标签 r dataframe apply

我找不到一个令人满意的教程来解释我如何使用应用函数的所有可能性。我仍然是新手,但这通常会派上用场,并显着简化我的代码。所以这是我的例子......
我有一个如下所示的数据框:

> head(p01)
   time key dwell
1   8.13   z  0.00
3   8.13   x  1.25
5   9.38   l  0.87
7  10.25   x  0.15
9  10.40   l  1.13
11 11.53   x  0.45

将其放入 R:
p01 <- structure(list(time = c(8.13, 8.13, 9.38, 10.25, 10.4, 11.53), 
key = c("z", "x", "l", "x", "l", "x"), dwell = c(0, 1.25, 
0.869, 0.15, 1.13, 0.45)), .Names = c("time", "key", "dwell"), row.names = c(1L, 3L, 5L, 7L, 9L, 11L), class = "data.frame")

现在我想计算 p01$key 中每个字母的出现次数并将它们打印在 p01$occurences ,所以结果看起来像这样:
    time key dwell occurences
1   8.13   z  0.00          1
3   8.13   x  1.25          3
5   9.38   l  0.87          2
7  10.25   x  0.15          3
9  10.40   l  1.13          2
11 11.53   x  0.45          3

我现在的做法是:
p01[p01$key == "l", "occurences"] <- table(p01$key)["l"]
p01[p01$key == "x", "occurences"] <- table(p01$key)["x"]
p01[p01$key == "z", "occurences"] <- table(p01$key)["z"]

...这当然不是最好的解决方案。特别是真实数据在p01$key中包含了更多的可能性。 (16 个不同的字母之一)。

最重要的是,我想计算总数 dwell对于每个字母,我现在正在做的是:
p01[p01$key == "l", "total_dwell"] <- tapply(p01$dwell, p01$key, sum)["l"]
p01[p01$key == "x", "total_dwell"] <- tapply(p01$dwell, p01$key, sum)["x"]
p01[p01$key == "z", "total_dwell"] <- tapply(p01$dwell, p01$key, sum)["z"]

为了得到:
    time key dwell total_dwell
1   8.13   z  0.00        0.00
3   8.13   x  1.25        1.85
5   9.38   l  0.87        2.00
7  10.25   x  0.15        1.85
9  10.40   l  1.13        2.00
11 11.53   x  0.45        1.85

在过去的 6 个小时里,我一直在谷歌搜索并浏览几本书。将非常感谢一个优雅的解决方案和/或一些综合教程的链接。
我的解决方案显然有效,但这不是我第一次解决这样的问题,我的脚本文件开始看起来很荒谬!

最佳答案

如果您的数据集很大,请尝试 data.table。

library(data.table)
DT <- data.table(p01)
DT[,occurences:=.N,by=key]
DT[,total_dwell:=sum(dwell),by=key]

    time key dwell occurences total_dwell
1:  8.13   z 0.000          1       0.000
2:  8.13   x 1.250          3       1.850
3:  9.38   l 0.869          2       1.999
4: 10.25   x 0.150          3       1.850
5: 10.40   l 1.130          2       1.999
6: 11.53   x 0.450          3       1.850

通过引用分配的两行可以组合如下:
DT[, `:=`(occurences = .N, total_dwell = sum(dwell)), by=key]

关于r - 使用 R 的应用函数之一简化代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16150124/

相关文章:

python - Pandas 数据帧 : using the output of a function in row x as input for the same function in row x+1

r - 训练期间的节点排序算法(R : randomForest)

r - 如何根据另一个数据框的列中的值对列名进行排序?

r - 通过矩阵的列查找满足某些标准的值的百分比

python - 有效地转换 Pandas 中的数据

r - 使用 R 从数据框中提取唯一值

python - .apply 在 Pandas 中如何工作?

python - 如何将不返回数值的函数应用于 Pandas 滚动窗口?

r - 一种指示每行多个指标变量的有效方法?

r - plotRGB 添加标题