У меня есть простая функция ggplot, которая рисует стрелки двойного графика от ординации кепка. Я понимаю, что есть встроенные веганские пакеты, и даже 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)
Что я действительно хотел бы здесь сделать, так это изменить «выбор», чтобы я мог построить график CAP1 против CAP3. В настоящее время, если я бегу
myplotcap(vare.cap, choices = c(1,3))
Ошибка в FUN(X[[i]], ...): объект 'CAP2' не найден
R запутался, потому что он ищет CAP2, а объект функции scores фактически переименовывает второй столбец в 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
}
За исключением использования синтаксиса, который действительно работает. Любые предложения здесь?
aes_string()
вместоaes()
для передачи имен столбцов в виде строк в ggplot. - person MrFlick   schedule 02.10.2017as.object
наget
в моем коде выше творит чудеса. - person ohnoplus   schedule 02.10.2017