Reputation: 589
I have a data frame which I can not reproduce and with the columns [col1,col2,...] being numeric values. When I try to plot one of the columns:
hist(df[,"col1"])
I get the following error:
Error in hist.default(df[, var]) : 'x' must be numeric*
But I can plot it when subsetting the data frame like this:
hist(df$col1]
This is not happening when plotting a boxplot
Upvotes: 0
Views: 1200
Reputation: 388807
Mostly probably your df
is not dataframe but a tibble.
When you subset a dataframe with one-colum you get a vector back.
mtcars[, 'mpg']
[1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 10.4
[17] 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7 15.0 21.4
This works fine with hist
:
hist(mtcars[,"mpg"])
which is same as doing
hist(mtcars$mpg)
But if you have a tibble, subsetting tibble by one-column returns a tibble back.
df <- tibble::tibble(mtcars)
df[,"mpg"]
# A tibble: 32 x 1
# mpg
# <dbl>
# 1 21
# 2 21
# 3 22.8
# 4 21.4
# 5 18.7
# 6 18.1
# 7 14.3
# 8 24.4
# 9 22.8
#10 19.2
# … with 22 more rows
So you get the error :
hist(df[,"mpg"])
Error in hist.default(df[, "mpg"]) : 'x' must be numeric
In which case you should use [[
to get a vector/
hist(df[["mpg"]])
Upvotes: 1