Home > OS >  Is there an easy way to enter/edit code in Rstudio? Avoiding repetition?
Is there an easy way to enter/edit code in Rstudio? Avoiding repetition?

Time:02-08

So I have the following code, as you can see this command will not run in R because it is missing a comma after each word and furthermore since these are characters I would need to enter a " before and after each word. Rather than going to each word and typing a " before and after and then a comma - is there an easy way to do this? I couldn't find a command that makes this easier from Rstudio's site - or I don't understand which one I need to use.

base_pckgs <- c(
    base
    compiler
    datasets
    graphics
    grDevices
    grid
    methods
    parallel
    splines
    stats
    stats4
    tcltk
    tools
    translations

)

Desired Output (without actually typing in a " and , in each row.

CodePudding user response:

Check out the datapasta add-in on CRAN or at https://github.com/MilesMcBain/datapasta. It adds some handy tools to RStudio's Addins menu. One, for instance, will let you paste your long list of packages as a vector:

c("base", "compiler", "datasets", "graphics", "grDevices", "grid", "methods", "parallel", "splines", "stats", "stats4", "tcltk", "tools", "translations")

CodePudding user response:

If you are wanting to load a list of libraries, then you could put the list into read.table, then turn it into a list, then use lapply to load all libraries.

read.table(text = "
  base
  compiler
  datasets
  graphics
  grDevices
  grid
  methods
  parallel
  splines
  stats
  stats4
  tcltk
  tools
  translations
  ") %>% 
  .[,1] %>% 
  lapply(., require, character.only = TRUE)

Or if you are wanting a quick way to add quotes and commas to create a vector, then you can use a combination of scan and dput.

dput(scan(text = "
  base
  compiler
  datasets
  graphics
  grDevices
  grid
  methods
  parallel
  splines
  stats
  stats4
  tcltk
  tools
  translations
  ", what=""))

c("base", "compiler", "datasets", "graphics", "grDevices", "grid", 
"methods", "parallel", "splines", "stats", "stats4", "tcltk", 
"tools", "translations")

This could also be piped into lapply too:

dput(scan(text = "
  base
  compiler
  datasets
  graphics
  grDevices
  grid
  methods
  parallel
  splines
  stats
  stats4
  tcltk
  tools
  translations
  ", what="")) %>% 
  lapply(., require, character.only = TRUE)
  •  Tags:  
  • Related