Edit:我将 Var4 更改为字符串值,因为我的问题对我的数据不够精确,因此由于类型无效,答案失败。对此感到抱歉
这是我的第一个问题,我希望有人可以帮助我。
我有以下数据集:
ID |
Date |
N_Date |
Var1 |
Var2 |
Var3 |
Var4 |
type |
1 |
4.7.22 |
50000 |
12 |
NA |
NA |
NA |
normal |
1 |
4.7.22 |
50000 |
NA |
23 |
NA |
NA |
normal |
1 |
4.7.22 |
50000 |
NA |
NA |
5 |
NA |
normal |
1 |
4.7.22 |
50000 |
NA |
NA |
NA |
asd |
normal |
2 |
4.7.22 |
50000 |
NA |
2 |
NA |
NA |
normal |
3 |
5.7.22 |
20000 |
7 |
NA |
NA |
NA |
normal |
我的目标是每个 ID 只占一行。所以我希望 R 做的是将每个 ID 的 Var 列值向上移动或以某种方式组合它们。正如您所看到的,目前,每一行的 Var 列中永远不会有多个值。因此,用相应的“实际值”重写 NA 应该很容易。我还发现了类似的问题,但答案对我的情况没有帮助:
如何合并具有相同标识符 R 的行? https://stackoverflow.com/questions/51523082/how-to-combine-rows-with-the-same-identifier-r
我认为我的情况的问题是,我有“日期”、“N_date”(这是该日期的观察次数)和“类型”等列。在这些情况下,我的代码应该看到,它与相应 ID 的值完全相同,并且仅以第一个值为例。
所以最后我只有 3 行,列数相同,包含所有信息。
非常感谢任何知道如何解决这个问题的人。
像这样的事情:
在这里,我们首先对除Var
变量,然后我们使用summarise(across...
正如评论部分@Limey 所建议的。
主要特点是使用na.rm=TRUE
:
library(dplyr)
df %>%
group_by(ID, Date, N_Date, type) %>%
summarise(across(starts_with("Var"), ~sum(., na.rm = TRUE)))
ID Date N_Date type Var1 Var2 Var3 Var4
<int> <chr> <int> <chr> <int> <int> <int> <int>
1 1 4.7.22 50000 normal 12 23 5 54
2 2 4.7.22 4000 normal 0 2 0 0
3 3 5.7.22 20000 normal 7 0 0 0
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)