Reputation: 315
I'm in R and want to subtract two vectors term by term.
Here are my code
y <- faithful
u_old1 <- c(3.5,80)
# eruptions waiting
#1 3.600 79
#2 1.800 54
#3 3.333 74
# ...
y - u_old1
# eruptions waiting
#1 0.100 75.5
#2 -78.200 -26.0
#3 -0.167 70.5
# ...
I think it's the recycling in R that does is. I want each row of y
minus u_old1
. So I should get the first row as:
# eruptions waiting
#1 0.100 -1
Upvotes: 2
Views: 120
Reputation: 93813
This is what sweep
was made for:
sweep(y, 2, u_old1)
# eruptions waiting
#1 0.100 -1
#2 -1.700 -26
#3 -0.167 -6
# ...
Upvotes: 2
Reputation: 193527
If I understand your question correctly, you should use as.list(u_old1)
instead:
Example:
head(y) - as.list(u_old1)
# eruptions waiting
# 1 0.100 -1
# 2 -1.700 -26
# 3 -0.167 -6
# 4 -1.217 -18
# 5 1.033 5
# 6 -0.617 -25
Upvotes: 1