-1

Hi all I am a novice to R and appreciate your hints on this case. I've been struggling to convert the variables (objects) in my dataframe to strings and plot them using a for loop, as detailed below.

COUNTRY: China Belgium ...
COMPANY: XXX Inc. YYY Inc. ...

Here, COUNTRY and COMPANY are categorical variables.

I've used toString() as well as as.character() to convert variable name to a string so I can specify the plot name but I cant seem to get it to work. I need 4 variable as listed in code below in for loop for 2 purposes:

  • as String for naming plot
  • use in barplot()

but neither string conversion nor the for loop is working properly as I meant to. Could somebody assist me with the proper command for this purpose? Your help is greatly appreciated... Kind regards,

CODE

Frequency_COUNTRY <- table(COUNTRY)#Get Frequency for COUNTRY 
Relative_Frequency_COUNTRY <- table(COUNTRY) / length(COUNTRY)#Get Relative 
#Frequency (Percentage %) for Variable COUNTRY
Frequency_COMPANY <- table(COMPANY) #Get Frequency and Relative Frequency for COMPANY
Relative_Frequency_COMPANY <- table(COMPANY) / length(COMPANY)
Categorical_Variable_List = c(Frequency_COUNTRY,
                        Relative_Frequency_COUNTRY ,
                        Frequency_COMPANY,
                        Relative_Frequency_COMPANY)`# Get list of 4 variables above
for (Categorical_Variable in Categorical_Variable_List){#Plot 4 variables using a for loop
     A = toString(Categorical_Variable) #Trying to convert non-string variable name to string
plotName <- paste("BarChart_", A, sep = "_")# Specify plot name, e.g. BarChart_Frequency_COUNTRY
png(file = plotName)#Create png file 
barplot(Categorical_Variable) #use barplot() to make graph
dev.off()`# Switch off dev
}   
Riccardo
  • 115
  • 11
  • I can't read your question. Please fix the formatting. Each line of code should receive four or more spaces at the start. DON'T put backticks around your code. – Tim Biegeleisen Dec 17 '18 at 06:24
  • Also, please use `dput` on your data frame/ a sample of it and upload it here – Omry Atia Dec 17 '18 at 06:27
  • Dear Omry Atia. I have now used dput to generate a sample dataframe. It is now in my Environment Variable. I cant seem to save it. Could you elaborate a bit on how to save and upload it? Many thanks! – Riccardo Dec 17 '18 at 07:31
  • @Riccardo Please read the accepted answer [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for how the site users here expect `dput()` output. – Z.Lin Dec 17 '18 at 08:14
  • 1) Your `Categorical_Variable_List` is **not** categorical at all. 2) Use `Categorical_Variable_List <- list(...)`, not `c(...)`. – Rui Barradas Dec 17 '18 at 09:50
  • @RuiBarradas. Hi Rui, many thanks for replying to my query. I'm using `list(Frequency_COUNTRY,...)` as you indicated, however, toString() does not output the name of the object i.e. "Frequency_COUNTRY" as string. Instead, it generates a string of Values in frequency table as shown below: `toString(Frequency_Country)` >>> [1] "1, 5, 4, 4, 1, 2, 2, 3, 9, 1, 13, 2, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 7, 52, 1". I actually intend to convert the object name Frequency_Country, which is a frequency table of countries, to a string, so I can use it to name my plot. – Riccardo Dec 18 '18 at 01:43
  • @RuiBarradas Hi Rui. Many thanks for taking time correcting the code.It's now working properly. Just one last query. I noticed you are using [[ i ]] in `Variable_List[[i]]`. was wondering why [i] wouldnt work. Is that because we use `(Frequency_COUNTRY = Frequency_COUNTRY` ... in the list() ? You did same for `Variable_Name[[i]]` However, at console when I do: `Variable_Name[1]`, I'm getting the desired name of the object: `[1] "Frequency_Country"`, which serves my purpose just fine. Could you elaborate a little bit on the usage of double square brackets [[ ]]. Many thinks in advance. Cheers. – Riccardo Dec 19 '18 at 01:17
  • Check out [R for data Science](https://r4ds.had.co.nz/vectors.html#lists-of-condiments). – Rui Barradas Dec 19 '18 at 11:57
  • @RuiBarradas. Many thanks :) – Riccardo Dec 21 '18 at 06:46

1 Answers1

0

Your code is treating Categorical_Variable_List as if it were a named list of categorical variables. It is neither.

The following code corrects those errors and plots a graph of 4 barplots. In your code, remove the two calls to par, one before and the other after the for loop.

I will make up a dataset, to test the code.

set.seed(1234)

n <- 20
COUNTRY <- sample(LETTERS[1:5], n, TRUE)
COMPANY <- sample(letters[1:4], n, TRUE)

Frequency_COUNTRY <- table(COUNTRY)    # Get Frequency for COUNTRY 
Relative_Frequency_COUNTRY <- table(COUNTRY) / length(COUNTRY)#Get Relative 
# Frequency (Percentage %) for Variable COUNTRY
Frequency_COMPANY <- table(COMPANY)    # Get Frequency and Relative Frequency for COMPANY
Relative_Frequency_COMPANY <- table(COMPANY) / length(COMPANY)

Variable_List <- list(Frequency_COUNTRY = Frequency_COUNTRY,
                      Relative_Frequency_COUNTRY = Relative_Frequency_COUNTRY,
                      Frequency_COMPANY = Frequency_COMPANY,
                      Relative_Frequency_COMPANY = Relative_Frequency_COMPANY) # Get list of 4 variables above
Variable_Name <- names(Variable_List)

old_par <- par(mfrow = c(2, 2))
for (i in seq_along(Variable_List)){                  # Plot 4 variables using a for loop
  plotName <- paste("BarChart", Variable_Name[[i]], sep = "_") # Specify plot name

  print(plotName)                                     # for debugging only

  #png(file = plotName)                               # Create png file 
  barplot(Variable_List[[i]])                         # use barplot() to make graph
  #dev.off()                                          # Switch off dev
}
par(old_par)

enter image description here

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66