我是 R 的新手(到目前為止編碼差不多一周)。對于這個簡單的問題,我深表歉意。我正在嘗試撰寫一個簡單的函式,該函式將根據我要輸入的資料集的變數創建一個餅圖。
資料集是
ID<-c("001","002","003","004","005","006","007","008","009","010","NA","012","013")
Name<-c("Damon Bell","Royce Sellers",NA,"Cali Wall","Alan Marshall","Amari Santos","Evelyn Frye","Kierra Osborne","Mohammed Jenkins","Kara Beltran","Davon Harmon","Kaitlin Hammond","Jovany Newman")
Sex<-c("Male","Male","Male",NA,"Male","Male",NA,"Female","Male","Female","Male","Female","Male")
Age<-c(33,27,29,26,27,35,29,32,NA,25,34,29,26)
data1<-data.frame(ID,Name,Sex,Age)
沒有該功能的代碼是:
#calculation of counts
dSex <- data %>%
filter(!is.na(Sex)) %>%
group_by(Sex) %>%
summarise(Count = n()) %>%
mutate(Total = sum(Count), Percentage = round((Count/Total),3))
## Compute the position of labels
dSex <- dSex %>%
arrange(desc(Sex)) %>%
mutate(ypos = cumsum(Percentage)-0.5*Percentage)
dSex %>%
ggplot(aes(x="", y=Percentage, fill=Sex))
geom_bar(stat="identity", color="White")
coord_polar("y", start=0)
geom_text(aes(y = ypos, label = paste0(round(Percentage*100,0),"%\n(", Count, ")")), color = "white")
scale_fill_manual(values = c("#7e0f7e", "#026b6c"))
guides(fill = guide_legend(title = "Sex"))
theme(
axis.title = element_blank(),
axis.line = element_blank(),
axis.text = element_blank()
)
所以我開始撰寫函式,我已經在苦苦掙扎了。我想以我稱之為“dSex”的新資料的名稱輸入變數 Sex,但我認為它不起作用。我把 deparse() 和替換() 放在一行,因為我的理解是它有助于 R 理解“Var”是函式的引數。而且我還放了雙“{”“}”,但它似乎沒有閱讀它!
FctPieChart <- function(dat,Var){
Var <- deparse(substitute({{Var}}))
dVar <- dat %>%
filter(!is.na({{Var}})) %>%
group_by(Var) %>%
summarise(Count = n()) %>%
mutate(Total = sum(Count), Percentage = round((Count/Total),3))
}
FctPieChart(data,Sex)
我收到以下錯誤:
Error: Problem with `filter()` input `..1`.
i Input `..1` is `!is.na(c("{", " {", " Sex", " }", "}"))`.
x Input `..1` must be of size 13 or 1, not size 5.
Run `rlang::last_error()` to see where the error occurred.
你對如何做到這一點有任何想法嗎?
還有一個小問題,我畫的餅圖很大,有沒有辦法縮小尺寸?
非常感謝您,如果有人有任何想法,這真的會幫助我!
最好的祝福,
斯蒂芬妮
基于以下建議的答案:答案是輸入字符中的變數(此處:)Sex作為函式的引數,并get()在我呼叫函式中的變數時使用該函式。get() 將允許我將字符轉換為變數。但是,該函式的使用get()導致變數名稱發生了變化:“ get(Var)”。我通過重命名資料中的變數并將第一個變數 Var 的副本創建為Var2.
我還想獲得一旦在函式中就停止創建的實際資料(它是在不在函式中的代碼中創建的)。我發現這dVar <<- dVar可以解決問題,因為它會創建資料。將呼叫資料 dVar并且名稱不依賴于輸入的變數(在舊代碼中是dSex)
由于我希望表的名稱能夠反映所使用的變數(而不是常規的“dVar”),因此我通過使用函式 assign() 和envir=.
更正后的代碼如下:
FctPieChart <- function(dat,Var){
#Create a replacement of `get(Var)` to use later
Var2 <-Var #We will use this one later instead of Var since Var is going to be changed into something else
print(Var2)
#Frequencies table
dVar <- dat %>%
filter(!is.na(get(Var))) %>%
group_by(get(Var)) %>% #changes the name of the column to "`get(Var)`"
summarise(Count = n()) %>%
mutate(Total = sum(Count), Percentage = round((Count/Total),3))
#Position calculation for the Pie Chart
dVar <- dVar %>%
arrange(desc(`get(Var)`)) %>%
mutate(ypos = cumsum(Percentage)-0.5*Percentage) print(dVar)
#Rename the variable that was changed in the data
colnames(dVar)<-c(Var2,"Count","Total","Percentage","ypos")
print(dVar)
#Make the graph
Graph <- dVar %>%
ggplot(aes(x="", y=Percentage, fill=get(Var2))) #fill=`get(Var)`) #get(Var2) alloWs to transform character into variable
geom_bar(stat="identity", color="White")
coord_polar("y", start=0)
geom_text(aes(y = ypos, label = paste0(round(Percentage*100,0),"%\n(", Count, ")")), color = "white")
scale_fill_manual(values = c("#7e0f7e", "#026b6c"))
guides(fill = guide_legend(title = Var2)) #title = Var2 takes the value as characters of Var2
theme(
axis.title = element_blank(),
axis.line = element_blank(),
axis.text = element_blank()
)
print(Graph)
#Create the table
dVar<<-dVar
#Change name of the data based on the variable
assign(paste0("d",Var2),dVar,envir = parent.frame()) #use envir = parent.frame() to access the environment outside the function, source: https://stackoverflow.com/questions/38296670/r-assign-inside-a-function
rm(dVar,envir = parent.frame())
}
FctPieChart(data,"Sex")
我要感謝幫助我解決問題的@Silentdevildoll。
祝你有美好的一天!
斯蒂芬妮
uj5u.com熱心網友回復:
我以前從未使用過這樣的東西,而且我的代碼中肯定存在缺陷,但這是我試圖幫助你的嘗試。我相信其他人會有更好的解決方案,但這至少是一個開始:
FctPieChart <- function(dat,Var){
dVar <- dat %>%
filter(!is.na(get(Var))) %>%
group_by(get(Var)) %>%
summarise(Count = n()) %>%
mutate(Total = sum(Count), Percentage = round((Count/Total),3))
dVar <- dVar %>%
arrange(desc(`get(Var)`)) %>%
mutate(ypos = cumsum(Percentage)-0.5*Percentage)
print(dVar)
dVar %>%
ggplot(aes(x="", y=Percentage, fill=`get(Var)`))
geom_bar(stat="identity", color="White")
coord_polar("y", start=0)
geom_text(aes(y = ypos, label = paste0(round(Percentage*100,0),"%\n(", Count, ")")), color = "white")
scale_fill_manual(values = c("#7e0f7e", "#026b6c"))
guides(fill = guide_legend(title = "Sex"))
theme(
axis.title = element_blank(),
axis.line = element_blank(),
axis.text = element_blank()
)
}
FctPieChart(data1,"Sex")
我對您使用的 deparse(substitute) 并不十分熟悉,但我知道這get()是一種將字串轉換為變數的方法,因此基本上我將函式第一段中的 Var 替換為 get(Var)。然而,我確信這并不理想,它group_by(get(Var))會將列的名稱更改為get(Var),我通過列印表格進行了演示。請注意,我還將變數輸入為“Sex”,而不僅僅是 Sex。就像我說的,這并不完美,但我認為這也許可以為您指明正確的方向。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409630.html
標籤:
