R中的条件数组
我有一个数据集,看起来像:R中的条件数组,r,R,我有一个数据集,看起来像: name, animal, price, type of intervention Kitty, Cat, 30.50, 1 Ralph, Cat, 12.75, 1 Squizz, Cat, 28.90, 2 Cash, Dog, 34.50, 2 Dexter, Dog, 42.30, 1 Tigger, Dog, 69.70, 1 Molly, Dog, 18.20, 2 我想根据各种条件绘制饼图 records <- read.csv("./examp
name, animal, price, type of intervention
Kitty, Cat, 30.50, 1
Ralph, Cat, 12.75, 1
Squizz, Cat, 28.90, 2
Cash, Dog, 34.50, 2
Dexter, Dog, 42.30, 1
Tigger, Dog, 69.70, 1
Molly, Dog, 18.20, 2
我想根据各种条件绘制饼图
records <- read.csv("./example.csv",sep=",",header=FALSE)
path="./"
setwd(path)
pdf("example.pdf",paper="a4", width=0,height=0)
name = records$V1
animal = records$V2
type = records$V4
animals=c(" Cat"," Dog")
for (type_id in 1:2){
nball <- c(sum(type==type_id & animal==animals[1]),sum(type==type_id & animal==animals[2]))
pct <- round(nball/sum(nball)*100)
pct <- round(nball/sum(nball)*100)
lbls <- paste(c(animals[1],animals[2]),pct)
lbls <- paste(lbls,"%",sep="")
col <- c("blue","red")
pie(nball, labels = lbls, main=NULL,col=col, cex.main=0.8,cex=1)
}
records我不确定我是否理解正确。您可能需要澄清所需的输出
您可以使用ggplot2和dplyr:
df <- data.table::fread("name, animal, price, type of intervention
Kitty, Cat, 30.50, 1
Ralph, Cat, 12.75, 1
Squizz, Cat, 28.90, 2
Cash, Dog, 34.50, 2
Dexter, Dog, 42.30, 1
Tigger, Dog, 69.70, 1
Molly, Dog, 18.20, 2")
library(ggplot2)
library(dplyr)
# filter and aggregate data
df <- df %>% group_by(`type of intervention`, animal) %>% summarise(S = n())
print_pie <- function(toi) {
pie <- ggplot(df %>% filter(`type of intervention` == toi), aes(x="", y=S, fill=animal)) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y", start=0)
print(pie)
}
print_pie(toi = 2)
df%摘要(S=n())
打印派我在运行示例时遇到问题,因此很难知道输出应该是什么样子——例如,变量“type\u id”没有定义,变量“sensor\u id”没有在循环中使用
df <- data.table::fread("name, animal, price, type of intervention
Kitty, Cat, 30.50, 1
Ralph, Cat, 12.75, 1
Squizz, Cat, 28.90, 2
Cash, Dog, 34.50, 2
Dexter, Dog, 42.30, 1
Tigger, Dog, 69.70, 1
Molly, Dog, 18.20, 2")
library(ggplot2)
library(dplyr)
# filter and aggregate data
df <- df %>% group_by(`type of intervention`, animal) %>% summarise(S = n())
print_pie <- function(toi) {
pie <- ggplot(df %>% filter(`type of intervention` == toi), aes(x="", y=S, fill=animal)) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y", start=0)
print(pie)
}
print_pie(toi = 2)
pies <- lapply(unique(df$`type of intervention`), print_pie)