Pass data CSV file to array in R (BARPLOT)

Posted on

Question :

I need to plot a chart in R by importing a csv file. After doing the csv import and calling the barplot it accuses the variable that I imported the csv is not a vector. So how do I transform into a vector to use in the barplot? I would like to use the header of each column to name the respective bar, how? The file is simple; only has 2 lines, one with the headers and another with the corresponding values.

I tried this way first:

    > data <- read.csv("tabela4_p2.csv", header = TRUE)
    > names <- c("Bancos", "Arborização", "EstComerc", "CasaResid","EdifResid", "ConstAband")

    barplot(as.integer(data$Bancos, data$Arborização, data$EstComerc, data$CasaResid, data$EdifResid, data$ConstAband), names.arg = names)

And you gave it here:

    Error in barplot.default(as.integer(data$Bancos, data$Arborização,data$EstComerc,: 
    número incorreto de nomes

Then I used it like this:

    barplot(data, names.arg = names)

And gave:

    Error in barplot.default(data, names.arg = names) : 
    'height' deve ser um vetor ou uma matriz


Answer :

I think what you want is something like this:

x <- data.frame(x = 1, y = 2, z = 3)
names(x) <- c("a", "b", "c")
barplot(height = as.numeric(x[1,]), names.arg = names(x))

Note that:

> as.integer(1,2,3)
[1] 1

In other words, it is a scalar and not a vector. Your code could work by doing:

barplot(as.integer(c(data$Bancos, data$Arborização, data$EstComerc, data$CasaResid, data$EdifResid, data$ConstAband)), names.arg = names)


Leave a Reply

Your email address will not be published. Required fields are marked *