gpt4 book ai didi

r - 在 R 中减去值时聚合

转载 作者:行者123 更新时间:2023-12-02 09:31:55 25 4
gpt4 key购买 nike

如果我在 R 中有两个数据帧(我们分别称它们为 df1df2),例如

> df1
state num1
AL 22
AK 49
AZ 48
AR 25

> df2
state num2
AK 2
AZ 3
AR 4
CA 5

我如何聚合这些数据帧,同时减去值以形成类似的东西

state num3
AL 22
AK 47
AZ 45
AR 21
CA -5

注意:数据框中的键值不相同;数据框有不同的行数

最佳答案

可能有更简单的方法到达那里,但这是一种可能性。我们可以merge() 两个数据帧,然后在将 NA 值替换为零后减去列。

m <- merge(df1, df2, all = TRUE)
cbind(m[1], num3 = with(replace(m, is.na(m), 0L), num1 - num2))
# state num3
# 1 AK 47
# 2 AL 22
# 3 AR 21
# 4 AZ 45
# 5 CA -5

数据:

df1 <- structure(list(state = structure(c(2L, 1L, 4L, 3L), .Label = c("AK", 
"AL", "AR", "AZ"), class = "factor"), num1 = c(22L, 49L, 48L,
25L)), .Names = c("state", "num1"), row.names = c(NA, 4L), class = "data.frame")

df2 <- structure(list(state = structure(c(1L, 3L, 2L, 4L), .Label = c("AK",
"AR", "AZ", "CA"), class = "factor"), num2 = 2:5), .Names = c("state",
"num2"), row.names = 2:5, class = "data.frame")

关于r - 在 R 中减去值时聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32161689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com