根据组中的其他变量为数据框中的每个组创建一个摘要行
相当新的R,最终处于以下情况下:我想根据年
和model
创建数据框中的每个组摘要行每行的值将基于一个value
的变量的减法。
df <- data.frame(Model = c(1,1,1,2,2,2,2,2,2,2,2,2,2),
Year = c(2020, 2020, 2020, 2020, 2020, 2020, 2020, 2030, 2030, 2030, 2040, 2040, 2040),
Variable = c("A", "B", "C", "A", "B", "C", "D", "A", "C", "E", "A", "C", "D"),
value = c(15, 2, 5, 25, 6, 4, 4, 41, 24,1, 15, 3, 2))
我设法为每个组创建了一个新行,因此它已经具有年
和actible> variable
名称,但我使用:
df <- df %>% group_by(Model, Year) %>% group_modify(~ add_row(., Variable = "New", .before=0))
但是,我正在努力创建一个我想从中计算value
的方程式。
我想要拥有的而不是NAS: abd的值
在每个组中
都将感谢任何帮助。我在这里的第一个线程,请赦免任何不便。
Fairly new to R, ended up in the following situation: I want to create a summary row for each group in the dataframe based on Year
and Model
, where a value
of each row would be based on the subtraction of value
of one Variable
from others in the group.
df <- data.frame(Model = c(1,1,1,2,2,2,2,2,2,2,2,2,2),
Year = c(2020, 2020, 2020, 2020, 2020, 2020, 2020, 2030, 2030, 2030, 2040, 2040, 2040),
Variable = c("A", "B", "C", "A", "B", "C", "D", "A", "C", "E", "A", "C", "D"),
value = c(15, 2, 5, 25, 6, 4, 4, 41, 24,1, 15, 3, 2))
I have managed to create a new row for each group, so it already has a Year
and a Variable
name that I manually specified using:
df <- df %>% group_by(Model, Year) %>% group_modify(~ add_row(., Variable = "New", .before=0))
However, I am struggling to create an equation from which I want to calculate the value
.
What I want to have instead of NAs: value
of A-B-D in each group
Would appreciate any help. My first thread here, pardon for any inconvenience.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以枢转,然后返回;这将添加与零缺少的零的行添加行:
编辑 - 变化,其中我们留下缺失的值并使用
cocece(x,0)
允许减法将Na视为零。pivot_wider
在缺少的点中创建na,但是我们可以在pivot_longer
中使用values_drop_na = true
将它们排除在pivot_longer
中。You could pivot wide and then back; this would add rows with zeros where missing:
EDIT - variation where we leave the missing values and use
coalesce(x, 0)
to allow subtraction to treat NA's as zeroes. Thepivot_wider
creates NA's in the missing spots, but we can exclude these in thepivot_longer
usingvalues_drop_na = TRUE
.