rowMeans function in dplyr
rowMeans function needs at least two dimensions
but DATA[,-1:-3]
is just one row.
[1] 2 4 60 80 200 400 600 10000 12000
You can get the Result by below code
DATA%>%
group_by(SITE, DATE) %>%
ungroup() %>%
mutate(NAYSA = rowMeans(.[,3:4]))
SITE DATE STUFF STUFF2 NAYSA
1 A 1 1 2 1.5
2 A 1 2 4 3.0
3 A 2 30 60 45.0
4 A 2 40 80 60.0
5 B 3 100 200 150.0
6 B 3 200 400 300.0
7 B 3 300 600 450.0
8 C 4 5000 10000 7500.0
9 C 4 6000 12000 9000.0
You need the rowwise
function in dplyr
to do that. Your data is random (because of sample) so it produces different results but you will see that it works:
library(dplyr)
group_by(DATA, SITE, DATE) %>%
mutate(STUFF=sample(STUFF,replace= TRUE), STUFF2 = sample(STUFF2,replace= TRUE))%>%
rowwise() %>%
mutate(NAYSA = mean(c(STUFF,STUFF2)))
Output:
Source: local data frame [9 x 5]
Groups: <by row>
SITE DATE STUFF STUFF2 NAYSA
1 A 1 1 2 1.5
2 A 1 2 2 2.0
3 A 2 30 80 55.0
4 A 2 30 60 45.0
5 B 3 200 600 400.0
6 B 3 300 200 250.0
7 B 3 100 600 350.0
8 C 4 5000 12000 8500.0
9 C 4 6000 10000 8000.0
As you see it calculates the rowwise mean per row, according to STUFF and STUFF2
@GregF Yep....ungroup()
was the key. Thanks.
Working code
RESULT = group_by(DATA, SITE, DATE) %>%
mutate(STUFF = sample(STUFF,replace= TRUE),
STUFF2 = sample(STUFF2,replace= TRUE)) %>%
ungroup() %>%
mutate(NAYSA = rowMeans(.[,-1:-2]))
Now that dplyr has introduced across
, this can be accomplished with across
and base R's rowMeans
. The following code will take the row-wise average of columns starting with the string "STUFF":
DATA %>%
mutate(NAYSA = rowMeans(across(starts_with("STUFF"))))