繁体   English   中英

R-将数据帧传递给功能

[英]R - Passing data frame to function

R初学者在这里。 我试图自己编写一个函数,该函数具有数据框作为参数,然后重新排序数据框,然后使用ggplot。 我一直在努力使该功能正常工作,而我似乎无法找到想要的答案。

我的第一个代码是这样的,

pareto_plot <- function(pareto_data, title, x_label, y_label, filename){
pareto_calc = pareto_data[order(-pareto_data[2]),]
colnames(pareto_calc) = c("sku", "volume")

pareto_calc$sku_perc = 1/length(pareto_calc$sku)
pareto_calc$sku_cum = cumsum(pareto_calc$sku_perc)

pareto_calc$vol_perc = pareto_calc$volume/sum(pareto_calc$volume)
pareto_calc$vol_cum = cumsum(pareto_calc$vol_perc)

ggplot(pareto_calc, aes(x=pareto_data$sku_cum, y=pareto_data$vol_cum)) +   geom_line(col="blue") + 
geom_line(y=0.8, col="red") +geom_line(x=0.2, col="red") + 
ggtitle(title) + ylab(y_label) + xlab(x_label)

ggsave(paste(filename,".png", sep=""))
}

使用上面的代码时,出现错误,

Error in eval(expr, envir, enclos) : object 'pareto_calc' not found

然后,我更改了代码以使用data因为我看到许多在线示例都将其用作参数。 我修改后的代码是

pareto_plot <- function(data, title, x_label, y_label, filename){
pareto_data = data

pareto_data[order(-pareto_data[2]),]
colnames(pareto_data) = c("sku", "volume")

pareto_data$sku_perc = 1/length(pareto_data$sku)
pareto_data$sku_cum = cumsum(pareto_data$sku_perc)

pareto_data$vol_perc = pareto_data$volume/sum(pareto_data$volume)
pareto_data$vol_cum = cumsum(pareto_data$vol_perc)

ggplot(pareto_data, aes(x=pareto_data$sku_cum, y=pareto_data$vol_cum)) +   geom_line(col="blue") + 
geom_line(y=0.8, col="red") +geom_line(x=0.2, col="red") + 
ggtitle(title) + ylab(y_label) + xlab(x_label)

ggsave(paste(filename,".png", sep=""))
}

有了这段代码,我现在得到了错误,

Error in exists(name, envir = env, mode = mode) : 
argument "env" is missing, with no default

任何帮助将不胜感激。 提前致谢! :)

当您创建一个函数时,通常最简单的做法是先编写代码,而不先使其成为一个函数,直到您确定它可以工作为止。 然后将其包装为一个函数。

set.seed(33)

df <- data.frame(V1 = runif(10),
                 V2 = rnorm(10))

pareto_plot <- function(data, title, x_label, y_label, filename){
        pareto_data <- data[order(-data[2]),] #you forgot to assign it

        names(pareto_data)  <-  c("sku", "volume")

        pareto_data$sku_perc  <-  1/length(pareto_data$sku)
        pareto_data$sku_cum <- cumsum(pareto_data$sku_perc)

        pareto_data$vol_perc <- pareto_data$volume/sum(pareto_data$volume)
        pareto_data$vol_cum <- cumsum(pareto_data$vol_perc)

        ggplot(pareto_data, aes(x=sku_cum, y=vol_cum)) +   geom_line(color="blue") + 
                geom_line(y=0.8, col="red") +geom_line(x=0.2, col="red") + 
                ggtitle(title) + ylab(y_label) + xlab(x_label)

        ggsave(paste(filename,".png", sep=""))
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM