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 string
s 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
}