用于在R中格式化和打印的函数
我目前正在尝试创建一个函数,该函数将正确格式化我的数据并返回已排序的条形图。但出于某种原因,我不断地犯下这样的错误:用于在R中格式化和打印的函数,r,ggplot2,R,Ggplot2,我目前正在尝试创建一个函数,该函数将正确格式化我的数据并返回已排序的条形图。但出于某种原因,我不断地犯下这样的错误: Error in `$<-.data.frame`(`*tmp*`, "Var1", value = integer(0)) : replacement has 0 rows, data has 3 “$一些注释中出现错误,您的函数无法工作,因为此部分不正确: order <- newDf[order(newDf$Freq, decreasing = FA
Error in `$<-.data.frame`(`*tmp*`, "Var1", value = integer(0)) :
replacement has 0 rows, data has 3
“$一些注释中出现错误,您的函数无法工作,因为此部分不正确:
order <- newDf[order(newDf$Freq, decreasing = FALSE), ]$Var1
它立即将您的列重命名为Var1
,但当您运行函数时,名称发生了变化。因此,为了避免这个问题,我建议您明确使用列名。在这个例子中,我使用了dplyr
库来简化我的生活。因此,按照您的代码和逻辑,它将如下所示:
newDf <- data %>% group_by_(col_name) %>% tally
order <- newDf[order(newDf$n, decreasing = FALSE), col_name][[col_name]]
data[,col_name] <- factor(data[,col_name], order)
plottingFunction <- function(data, col_name, xlabel, ylabel, header) {
#' create a dataframe with the data that we're interested in
#' make sure that you preserve the anme of the column that you're
#' counting on...
newDf <- data %>% group_by_(col_name) %>% tally
order <- newDf[order(newDf$n, decreasing = FALSE), col_name][[col_name]]
data[,col_name] <- factor(data[,col_name], order)
plot <- ggplot(data, aes_string(col_name)) +
xlab(xlabel) +
ylab(ylabel) +
ggtitle(header) +
geom_bar(fill="lightblue", colour="black") +
coord_flip()
return(plot)
}
plottingFunction(df, "x", "xlabel","ylabel","header")
这将产生如下输出:
我认为对于您的绘图,使用stat=“identity”
是多余的,因为您可以只使用原始数据帧,而不使用转换后的数据帧
newDf <- data %>% group_by_(col_name) %>% tally
order <- newDf[order(newDf$n, decreasing = FALSE), col_name][[col_name]]
data[,col_name] <- factor(data[,col_name], order)
plottingFunction <- function(data, col_name, xlabel, ylabel, header) {
#' create a dataframe with the data that we're interested in
#' make sure that you preserve the anme of the column that you're
#' counting on...
newDf <- data %>% group_by_(col_name) %>% tally
order <- newDf[order(newDf$n, decreasing = FALSE), col_name][[col_name]]
data[,col_name] <- factor(data[,col_name], order)
plot <- ggplot(data, aes_string(col_name)) +
xlab(xlabel) +
ylab(ylabel) +
ggtitle(header) +
geom_bar(fill="lightblue", colour="black") +
coord_flip()
return(plot)
}
plottingFunction(df, "x", "xlabel","ylabel","header")