我是R的新手,希望有人可以在下面的代码中向我解释两件事。
{{
才能将它转到recordPlot,以便重播?然后我需要在replayPlot中使用双方括号[[
。$
表示法?它在它之外工作。在“适当的”R工作中使用$是不是很糟糕?我的真实代码要大得多,所以最好还是选择合适的工作方式。
library(ggplot2)
library(gridExtra)
TDSF <- data.frame(Graduation=sample(1950:2010, 30,replace=TRUE),
Donation=sample(10:50000, 30,replace=TRUE),
Start.Year=sample(1950:2010,30,replace=TRUE),
State=sample(state.abb,30,replace=TRUE))
TDSF$Graduation <- as.numeric(as.character(TDSF$Graduation))
TDSF$Start <- as.numeric(as.character(TDSF$Start))
plots2 <- mapply(function(nm,df.year,df.bracket_5,df.bracket_10) list(
{{plot(-1:1,-1:1,type="n",xaxt="n",yaxt="n",ann=FALSE)+
text(0,0,paste("Analysis by",nm,"Year"),cex=2)
recordPlot()}},
{ggplot(data=TDSF, aes_(x=as.name(nm))) + geom_histogram(color="red",binwidth = 1,boundary=-.01)},
{ggplot(data=TDSF, aes_(x=as.name(nm))) + geom_histogram(color="red",binwidth = 5,boundary=-.01)}
),c("Graduation","Start"),SIMPLIFY = FALSE)
replayPlot(plots2$Graduation[[1]]) #use $ notation
do.call(grid.arrange,plots2$Graduation[2:3])`#use $ notation
mapply(function(nm)
{pdf(file=paste(nm,"test.pdf"))
replayPlot(plots2[[nm]][[1]]) #use [[]][[]]
do.call(grid.arrange,c(plots2[[nm]][2:3],ncol=1)) #use [[]][[]]
dev.off()}
,c("Graduation","Start"))
答案 0 :(得分:1)
让我重新格式化你的代码:
library(ggplot2)
library(gridExtra)
TDSF <- data.frame(Graduation=sample(1950:2010, 30,replace=TRUE),
Donation=sample(10:50000, 30,replace=TRUE),
Start.Year=sample(1950:2010,30,replace=TRUE),
State=sample(state.abb,30,replace=TRUE))
TDSF$Graduation <- as.numeric(as.character(TDSF$Graduation))
TDSF$Start <- as.numeric(as.character(TDSF$Start))
plots2 <- mapply(function(nm,df.year,df.bracket_5,df.bracket_10) list(
{plot(-1:1,-1:1,type="n",xaxt="n",yaxt="n",ann=FALSE)+
text(0,0,paste("Analysis by",nm,"Year"),cex=2)
recordPlot()},
{ggplot(data=TDSF, aes_(x=as.name(nm))) + geom_histogram(color="red",binwidth = 1,boundary=-.01)},
{ggplot(data=TDSF, aes_(x=as.name(nm))) + geom_histogram(color="red",binwidth = 5,boundary=-.01)}
),c("Graduation","Start"),SIMPLIFY = FALSE)
plots2
replayPlot(plots2$Graduation[[1]]) #use $ notation
n <- length(plots2)
nCol <- floor(sqrt(n))
do.call("grid.arrange",c(plots2$Graduation[2:3], ncol=nCol)) #use $ notation
replay <- function(nm) {
pdf(file = paste(nm,"test.pdf"))
replayPlot(plots2[[nm]][[1]]) #use [[]][[]]
do.call(grid.arrange,c(plots2[[nm]][2:3],ncol = 1)) #use [[]][[]]
dev.off()
}
mapply(replay ,c("Graduation","Start"))
您不需要双括号
双方括号用于依次访问元素。 plots2是一个相对复杂的结构,有很多方法可以访问它的元素
plots2$Graduation[[1]] is equivalent to plots2[[1]][[1]] for example