0

Upon executing this code, I get twelve rows of data with a new column A1. I want a functionality such, that for all "1" appearing in A1, I should get an average of the corresponding Sepal.Length values,similarly for "2" and "3" and the assign the three average values to a new vector. So in all, a vector with three average values based on the requirement above.

iris1 = iris[1:12,]
a = data.frame(A1=rep(1,4))
b = data.frame(A1=rep(2,4))
c = data.frame(A1 = rep(3,4))
abc = rbind(a,b,c)
abc
iris2 = data.frame(abc,iris1)
View(iris2)
Axeman
  • 32,068
  • 8
  • 81
  • 94
Ashmin Kaul
  • 860
  • 2
  • 12
  • 37
  • 1
    Do you mean group by A1, and get mean of Sepal.Length for every row? What is the expected output? – zx8754 Oct 27 '17 at 08:10
  • 2
    e.g. `sapply(split(iris2$Sepal.Length, iris2$A1), mean)` or `aggregate(Sepal.Length ~ A1, iris2, mean)`? – Axeman Oct 27 '17 at 08:14
  • Thanks Axeman, solved my problem perfectly. – Ashmin Kaul Oct 27 '17 at 08:27
  • Please help me with link, https://stackoverflow.com/questions/46972729/making-a-stacked-bar-plot-based-on-ranges-in-r-and-plotly/46972927?noredirect=1#comment80893631_46972927 – Ashmin Kaul Oct 27 '17 at 11:07

1 Answers1

0

try this

library(dplyr)
iris2 %>% group_by(A1) %>% summarise(Avg = mean(Sepal.Length,na.rm = TRUE))

and if you really just want the vector with the Averages

iris2 %>% group_by(A1) %>% summarise(Avg = mean(Sepal.Length,na.rm = TRUE)) %>% `$`(Avg)
Bertil Baron
  • 4,923
  • 1
  • 15
  • 24