Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

for loop - Question about R, How can take the mean of each category?

I am trying to write a code to count how many times each category is named and then take the mean of each category.
How would I go about this? A for loop? a if else ? a function?

So I want to write a code that counts every time I can see ''Location''. It stores and then tells me there is 4 within this category. Also I want to take the mean. so 4 divided by 25 = .16

"location"    "Masculinity" "ownership"   "Masculinity" "difference" 
"agency"      "agency"      "Feminality"  "ownership"   "Feminality" 
"ownership"   "location"    "agency"      "Masculinity" "difference" 
"location"    "Feminality"  "ownership"   "agency"      "Masculinity"
"difference"  "difference"  "Feminality"  "location"    "Masculinity"

Thank you.

question from:https://stackoverflow.com/questions/65875643/question-about-r-how-can-take-the-mean-of-each-category

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An option is also split the vec by the same object, get the lengths and divide by the length of the whole vector

lengths(split(vec, vec))/length(vec)
#   agency  difference  Feminality    location Masculinity   ownership 
#   0.16        0.16        0.16        0.16        0.20        0.16 

Or with count from dplyr

library(dplyr)
tibble(vec) %>%
    count(vec) %>% 
    mutate(prop = n/sum(n))
   

or use adorn_percentages from janitor

library(janitor)
tibble(vec) %>% 
    count(vec) %>%
    adorn_percentages("col")

data

vec <- c("location", "Masculinity", "ownership", "Masculinity", "difference", 
"agency", "agency", "Feminality", "ownership", "Feminality", 
"ownership", "location", "agency", "Masculinity", "difference", 
"location", "Feminality", "ownership", "agency", "Masculinity", 
"difference", "difference", "Feminality", "location", "Masculinity"
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...