Reputation: 37
I am completely lost right now with R. Been trying to teach it to myself for the past week now but I've been stuck with a pie chart problem for two days that I can't seem to figure out.
I have a table that has several columns. With two of which I want to create a pie chart. The first is called "Rabatt" and the second one is called "Gewinnspiel" now they can both either bei 0 for False or 1 for True but neither of the rows can have True in both columns. So the combinations can either be 00 10 or 01. Now I want a pie chart that shows the percentage for how many are 00, 10 or 01. But how do I tell R to only show percentages from both rows for when they contain the value 1 (since when they contain the value 0 they are False and irrelevant until they are both False), add these two up and then also show the percentage of those cases where both are 0?
I hope my explanation was somehow understandable.
Here is a part of the data (in total it's more then 100 rows).
Rabatt Gewinnspiel
0 0
0 0
0 0
1 0
1 0
1 0
0 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
0 1
0 1
1 0
1 0
0 0
Upvotes: 1
Views: 164
Reputation: 1867
Here is an example how it can be done with package dplyr
and table
function
your data
df = read.table(header = T, stringsAsFactors = F, text = "Rabatt Gewinnspiel
0 0
0 0
0 0
1 0
1 0
1 0
0 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
0 1
0 1
1 0
1 0
0 0")
you create new variable called ny_var by joining Rabatt and Gewinnspiel
df <- df %>% mutate(ny_var = paste(Rabatt, Gewinnspiel, sep = ""))
you plot your new variable as a pie chart
pie(table(df$ny_var))
you can take a look on your summarised data
table(df$ny_var)
Upvotes: 1
Reputation: 2101
If you don't want to use an additional package for this task and have your %-numbers in the label as well, try this (where df
is your data frame):
df <- read.table(text = "Rabatt Gewinnspiel
0 0
0 0
0 0
1 0
1 0
1 0
0 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
0 1
0 1
1 0
1 0
0 0", header = TRUE)
pie_tbl <- table(with(df, paste0(Rabatt, Gewinnspiel)))
pie(x = pie_tbl, labels = paste0(names(pie_tbl), ": ", round(pie_tbl/sum(pie_tbl)*100), "%"))
Upvotes: 1
Reputation: 20085
Here is a way:
#data
df <- read.table(text = "Rabatt Gewinnspiel
0 0
0 0
0 0
1 0
1 0
1 0
0 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
0 1
0 1
1 0
1 0
0 0", header = T, stringsAsFactors = F)
#Create a factor based on combination
df$Data <- as.factor(paste(df$Rabatt, df$Gewinnspiel, sep = ""))
library(dplyr)
#Calculate number of occurrence for each combination using summarise
df_mod <- df %>%
group_by(Data) %>%
summarise(Count = n())
#Draw pie
pie(df_mod$Count, df_mod$Data)
Upvotes: 0