gareth_t
gareth_t

Reputation: 15

Recursive boxplot in R returning invalid variable type error

I'm trying to plot multiple boxplots in R within a for loop but can't reference columns in the dataset using the data.frame[column]as it returns the following:

Error in model.frame.default(formula = e[1] ~ e[2]) : invalid type (list) for variable 'e[1]'

The following code returns the same error that I'm getting:

x <- rnorm(20)
y <- rnorm(20)
e <- data.frame(x, y)
boxplot(e[1] ~ e$y)

Any suggestions? I'm really stuck here.

Upvotes: 0

Views: 1538

Answers (2)

bdemarest
bdemarest

Reputation: 14667

There are two issues here:

1. As pointed out by @Sven Hohenstein, your boxplot call needs to reference data.frame columns correctly.

2. I think that you want two side by side boxplots (x and y), not x ~ y. For example:

# All these commands are equivalent:
boxplot(e$x, e$y)
boxplot(e[[1]], e[[2]])
boxplot(e[, 1], e[, 2])

# Probably not what you want:
boxplot(e$x ~ e$y)
boxplot(x ~ y, data=e)

Upvotes: 1

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

To access column x of data frame df, use

df[[x]]

or

df[ , x]

Upvotes: 1

Related Questions