[英]using mutate to create a new variable
我正在處理R中的數據集,該數據集處理的是名為points
的變量。 數據集包括籃球賽季的每場比賽,可變points
分為0、1、2和3分。 我想出要找出每支球隊得分的頻率。 現在,我需要使用mutate()
來創建一個名為Totalpoints
的新變量的Totalpoints
,該變量會將這些點相加,同時使point = 2
等於其頻率的2倍,而point = 3等於其頻率的3倍。 到目前為止,這是我的代碼:
Basketball1 <- Basketball %>%
select("TeamName","points")
Basketball1 %>%
mutate(totalpoints = (0*(Basketball1$points == "0"))+
(2*(Basketball1$points == "2"))+
(1*(Basketball1$points == "1"))+
(3*(Basketball1$points == "3")))
我需要創建這個新變量的幫助,這些變量在正確權衡它們的同時加總了這些點。
根據我假設您的數據集看起來或類似的情況,創建一個可復制的示例。 如果您想要獲得每個團隊的總積分,Ben Bolker的答案非常有用。
另外,如果您希望比較每個籃球隊產生的不同類型積分的頻率,或者希望查看每種積分對總積分的貢獻程度,則可能會有所幫助。
library(dplyr)
library(ggplot2)
points = c('1', '2', '3', '2', '1')
team_name <- c('rockets','rockets','rockets','rockets', 'rockets')
Basketball1 = as.data.frame(cbind(points, team_name))
# Create Reference column for point types and create a numeric column for multiplication
points_df <- Basketball1 %>% distinct(points) %>% mutate(points_num = as.numeric(points))
Basketball1 %>% group_by(., points, team_name) %>%
summarize(frequency_count = n()) %>%
left_join(points_df) %>% mutate(total_points = frequency_count * points_num) %>%
select(-points_num) -> Basketball_total_points
# Plot Distribution of total points by Type of point
Basketball_total_points %>% ggplot(aes(team_name, total_points,fill=as.factor(points))) + geom_bar(stat='identity')
# Plot Distribution of frequency by Type of point
Basketball_total_points %>% ggplot(aes(team_name, frequency_count,fill=as.factor(points))) + geom_bar(stat='identity')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.