Reputation: 315
I am new in R and I would like to get some help. I have an R code with user defined function called Plot_linear_fit below that I ran without any errors.
ReportDateRange <- c("2010-11-01", "2017-01-31")
trendDateRange1 <- c("2015-01-01", "2015-08-31")
trendDateRange2 <- c("2015-01-01", "2016-10-31")
trendDateRange3 <- c("2015-01-01", "2016-06-30")
plotDate1 <- c("2011-01-01")
plotDate2 <- c("2015-01-01")
plotDate3 <- c("2013-01-01")
numoftrends <- 3
TRx.Plot1 <- Plot_linear_fit(Sum.TRx,
trendDateRange1,
plotDate1,
ReportDateRange)
TRx.Plot2 <- Plot_linear_fit(Sum.TRx,
trendDateRange2,
plotDate2,
ReportDateRange)
TRx.Plot3 <- Plot_linear_fit(Sum.TRx,
trendDateRange3,
plotDate3,
ReportDateRange)
I would like to put these codes in a loop using lapply however when I try to run it, I am getting the NA/NAN argument
ReportDateRange <- c("2010-11-01", "2017-01-31")
trendDateRange1 <- c("2015-01-01", "2015-08-31")
trendDateRange2 <- c("2015-01-01", "2016-10-31")
trendDateRange3 <- c("2015-01-01", "2016-06-30")
plotDate1 <- c("2011-01-01")
plotDate2 <- c("2015-01-01")
plotDate3 <- c("2013-01-01")
numoftrends <- 3
lapply(1:numoftrends, function(j) {
paste0('TRx.Plot', j) <- Plot_linear_fit(Sum.TRx,
paste0("trendDateRange", j),
paste0("plotDate", j),
ReportDateRange)
})
I am not so sure what is wrong when you put this in lapply. The output of the function Plot_linear_fit is a dataframe. Thank you for your help.
Upvotes: 0
Views: 3911
Reputation: 12819
The minimal fix would be (I guess, untested code because you didn't provide a MRE):
lapply(1:numoftrends, function(j) {
assign(paste0('TRx.Plot', j),
Plot_linear_fit(Sum.TRx,
get(paste0("trendDateRange", j)),
get(paste0("plotDate", j)),
ReportDateRange),
pos = .GlobalEnv)
})
But it would be more idiomatic to drop assignments in the global workspace altogether, and work directly with lists:
list_of_plots <- lapply(1:numoftrends, function(j) {
Plot_linear_fit(Sum.TRx,
get(paste0("trendDateRange", j)),
get(paste0("plotDate", j)),
ReportDateRange)
})
Upvotes: 2