引用可能在ggplot中更改的函数列名称

时间:2017-10-02 19:14:03

标签: r ggplot2 vegan

我在这里有一个简单的ggplot函数,它绘制了一个capscale排序的双时隙箭头。我确实知道有内置素食包,甚至ggvegan为我这样做。这实际上最终成为一个更复杂的其他功能的一部分,我确实需要让这个适用于这个简单的情况。

## import packages
library(vegan)
library(ggplot)

## load in some toy data
data(varespec)
data(varechem)

## Basic capscale ordination
vare.cap <- capscale(varespec ~ N + P + K + Condition(Al), varechem,
                     dist="bray")

## Function takes the capscale object and plots out the biplot vectors
myplotcap <- function(cap, choices = c(1,2)){
                                        # Get biplot scores from capscale, turn them into a data frame
    scoresdf <- data.frame(scores(cap, display = c("bp"), choices = choices))
                                        # Add the rownames as their own column
    scoresdf <- mutate(scoresdf, Row.names = rownames(scoresdf))

    p <- ggplot(scoresdf) +
                                        # segments pointing from origin to biplot location
        geom_segment(aes(x = 0, y = 0, xend = CAP1, yend = CAP2)) +
                                        # lables
        geom_text(aes(x = CAP1 * 1.05, y = CAP2 * 1.05, label = Row.names))
    p
}

## Actually plot the function
myplotcap(vare.cap)

我真正想在这里做的是能够修改&#34;选择&#34;所以我可以绘制CAP1和CAP3。目前如果我跑

myplotcap(vare.cap, choices = c(1,3))
  

FUN中的错误(X [[i]],...):对象&#39; CAP2&#39;找不到

R感到困惑,因为它正在寻找CAP2,而得分函数对象实际上将第二列重命名为CAP3。

我想做一些事情,比如告诉R要查找的对象。

CAPaName <- paste("CAP", choices[1], sep = "")
CAPbName <- paste("CAP", choices[2], sep = "")

然后以某种方式将这些字符串转换为函数中的对象。有点像用CAP1替换as.object(CAPaName)的所有实例,所以我的函数看起来像:

myplotcap <- function(cap, choices = c(1,2)){
                                        # Get biplot scores from capscale, turn them into a data frame
    scoresdf <- data.frame(scores(cap, display = c("bp"), choices = choices))
                                        # Add the rownames as their own column
    scoresdf <- mutate(scoresdf, Row.names = rownames(scoresdf))

    p <- ggplot(scoresdf) +
                                        # segments pointing from origin to biplot location
        geom_segment(aes(x = 0, y = 0, xend = as.object(CAPaName), yend = as.object(CAPbName))) +
                                        # lables
        geom_text(aes(x = as.object(CAPaName) * 1.05, y = as.object(CAPbName) * 1.05, label = Row.names))
    p
}

除了使用实际有效的语法。这里有什么建议吗?

0 个答案:

没有答案