Home > Enterprise >  Issue with using a for loop to install packages with specific version? R
Issue with using a for loop to install packages with specific version? R

Time:03-11

I have the following dataframe

pckgs_needed <- data.frame("package" = c("qwraps2", "arm", "psych", "caret"),
                           "version" = c("0.4.2", "1.11-1", "1.9.12.31", "6.0-86"))

I'm trying to use a for loop to install these packages through the remotes::install.packages() command.

Although it looks like my loop is not working properly.

for(i in pckgs_needed$package){
  for(j in pckgs_needed$version) {
    install_version(i, version = j, repos = "http://cran.us.r-project.org")
    
  }
}

My goal is too essentially pass the matching package and version though the loop and install the version of the package needed.

Although it looks like its trying to install each package by each version in the dataframe based off the error I am receiving Error in download_version_url(package, version, repos, type) : version '1.11-1' is invalid for package 'qwraps2' and based off this second loop

for(i in pckgs_needed$package){
  for(j in pckgs_needed$version) {
    print(paste(i," ", j))
    
  }
}

CodePudding user response:

You need to apply the function respectively instead of creating all possible pairs of package name and versions as it would be archived using nested for loops:

mapply(function(x, y) remotes::install_version(package = x, version = y), 
  pckgs_needed$package, pckgs_needed$version)

CodePudding user response:

You can also use the versions r package as well and pass a vector to packages and version instead of looping. However, this only works if the package you want was after 2014-09-17 when MRAN was launched.

library(versions)
install.versions(pkgs = pckgs_needed$package, version = pckgs_needed$version)
 
  •  Tags:  
  • r
  • Related