Pass data CSV file to array in R (BARPLOT)

Asked

Viewed 279 times

3

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

I tried so 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 gave this 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

1 answer

4


I believe 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))

inserir a descrição da imagem aqui

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)

See that inside the as.integer put the function c that concatenates the elements, before you call the as.integer.

  • Returned the following: ** Error in barplot.default(as.integer(c(date$Banks, date$Afforestation, date$Estcomerc, : incorrect number of names **

  • its base actually has a row and the same number of columns as the Names vector?

  • The table is like this and I did as you put it: Banks Afforestation Estcomerc Casaresid Edifresid Constaband 112 22 80 72 40 11

  • 1

    I was doing the wrong thing! It worked too well! Vlw!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.