So, I have a process that I currently use Excel for, and I want to find the most efficient way to do it in R.
My data take this shape:
ID <- c(rep(1, 3), rep(2, 3))
Source <- rep(c("A", "A", "B"), 2)
Total <- c(11, 13, 12, 25, 27, 26)
Actions <- c(3, 2, 3, 8, 9, 10)
df <- data.frame(ID, Source, Total, Actions)
df
# ID Source Total Actions
# 1 1 A 11 3
# 2 1 A 13 2
# 3 1 B 12 3
# 4 2 A 25 8
# 5 2 A 27 9
# 6 2 B 26 10
I run an aggregate on Total
and Actions
:
df2 <- aggregate(cbind(Total, Actions) ~ ID + Source,
data = df, FUN=sum)
df2
# ID Source Total Actions
# 1 1 A 24 5
# 2 2 A 52 17
# 3 1 B 12 3
# 4 2 B 26 10
But what I really want is a situation where the totals for A and totals for B are separate columns in the same table. Currently I am doing it like this:
df2_A <- df2[(df2$Source == "A"), ]
df2_B <- df2[(df2$Source == "B"), ]
x <- merge(df2_A, df2_B, by.x = "ID", by.y = "ID")
x
# ID Source.x Total.x Actions.x Source.y Total.y Actions.y
# 1 1 A 24 5 B 12 3
# 2 2 A 52 17 B 26 10
My question is, is there a more elegant way to go from df
to x
in one step? I feel like what I am doing now is a crude hack, and I want to expand my R knowledge.