I'm trying to use a for loop to create a set of dynamic objects in R. These will contain a list of organisations and values against a certain metric--each output will be the values of an individual metric.
In practice, this will be used to create chart objects using ggplot2, which I'll then use in RMarkdown. For the example below, it's just a sample using a head() function for each metric.
I tried using the paste function to create this name, but it gives the following error:
Error in paste("organisation_short", "_", MetricIDs[x]) <- head(organisationdata_Jan2021) : target of assignment expands to non-language object
I understand that the assign function might help, but I'm not sure how to use it. (My attempts also produced errors). I found a similar question in the link below, but it's set up in a way that pipes data directly into assign. I'm also not clear what "value = ." is doing. This query is below: dynamically name objects in R
I believe the "value = ." refers to the data being piped into the assign function. I created an alternative version which is in the code below.
Error in assign(x = organisationdata_Jan2021, value = paste0("sampledata", : invalid first argument
The idea is to create output files along the lines of: organisation_short_ABC123, organisation_short_ABC323, organisation_short_KJM088
I would be grateful for any guidance you might have!
MetricIDs <- c('ABC123','ABC323','KJM088')
# Attempt using paste
for (x in 1:3)
{
organisationdata_Jan2021 <- organisationdata_CM0040_Jan2021 %>% filter(Metric_ID==MetricIDs[x]) # Filter data to specific Metric ID
paste("organisation_short","_", MetricIDs[x]) <- head(organisationdata_Jan2021) # Goal: Create object that includes the Metric ID.
}
# Attempt using assign
for (x in 1:3)
{
organisationdata_Jan2021 <- organisationdata_CM0040_Jan2021 %>% filter(Metric_ID==MetricIDs[x]) # Filter data to specific Metric ID
assign(x=organisationdata_Jan2021, value=paste0("sampledata",MetricIDs[x]))
}
# Expected object names: organisation_short_ABC123, organisation_short_ABC323, organisation_short_KJM088
# This will be used to create chart objects using ggplot2, and those objects will be used in an R MarkDown document.