0

I would like to better visualize a set of data I created in R using the barplot() function. However, I am unsure how to go about this procedure based on 2 columns in a data frame.

name of my data frame: myData

Below is the contents of my data frame:

   States Churn
1      AK     3
2      AL     8
3      AR    11
4      AZ     4
5      CA     9
6      CO     9
7      CT    12
8      DC     5
9      DE     9
10     FL     8
11     GA     8
12     HI     3
13     IA     3
14     ID     9
15     IL     5
16     IN     9
17     KS    13
18     KY     8
19     LA     4
20     MA    11
21     MD    17
22     ME    13
23     MI    16
24     MN    15
25     MO     7
26     MS    14
27     MT    14
28     NC    11
29     ND     6
30     NE     5
31     NH     9
32     NJ    18
33     NM     6
34     NV    14
35     NY    15
36     OH    10
37     OK     9
38     OR    11
39     PA     8
40     RI     6
41     SC    14
42     SD     8
43     TN     5
44     TX    18
45     UT    10
46     VA     5
47     VT     8
48     WA    14
49     WI     7
50     WV    10
51     WY     9

Basically, I would like to create a barplot showing the value of 3 for AK, 8 for AL, 11 for AR,and so on.

I tried: barplot(myData) but I get the error message Error in barplot.default(myData) : 'height' must be a vector or a matrix

Mike
  • 53
  • 7
  • If you search for the error message, you should get lots of posts on it, including https://stackoverflow.com/q/47986939/5325862, https://stackoverflow.com/q/16617365/5325862, https://stackoverflow.com/q/36759077/5325862, https://stackoverflow.com/q/31079509/5325862, and https://stackoverflow.com/q/23369772/5325862 – camille Feb 18 '20 at 04:30

1 Answers1

1

If we are passing a single parameter, then it can be a named vector

barplot(setNames(myData$Churn, myData$States))

Or otherwise, it can be a formula method

barplot(Churn ~ States, myData)

data

myData <- structure(list(States = c("AK", "AL", "AR", "AZ", "CA", "CO", 
"CT", "DC", "DE", "FL", "GA", "HI", "IA", "ID", "IL", "IN", "KS", 
"KY", "LA", "MA", "MD", "ME", "MI", "MN", "MO", "MS", "MT", "NC", 
"ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", 
"RI", "SC", "SD", "TN", "TX", "UT", "VA", "VT", "WA", "WI", "WV", 
"WY"), Churn = c(3L, 8L, 11L, 4L, 9L, 9L, 12L, 5L, 9L, 8L, 8L, 
3L, 3L, 9L, 5L, 9L, 13L, 8L, 4L, 11L, 17L, 13L, 16L, 15L, 7L, 
14L, 14L, 11L, 6L, 5L, 9L, 18L, 6L, 14L, 15L, 10L, 9L, 11L, 8L, 
6L, 14L, 8L, 5L, 18L, 10L, 5L, 8L, 14L, 7L, 10L, 9L)), 
class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", 
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", 
"25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", 
"36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", 
"47", "48", "49", "50", "51"))
akrun
  • 874,273
  • 37
  • 540
  • 662