0

I want to specify multiple columns to save each as a vector, but I don't want a bunch of lines of code just to save each column. For example,

Instead of:

sl <- iris["Sepal.Length"]
sw <- iris["Sepal.Width"]

Something like:

c(sl, sw) <- c(iris["Sepal.Length"], iris["Sepal.Width"])

That's how I expect to be able to do this, but it doesn't work.

conv3d
  • 2,668
  • 6
  • 25
  • 45
  • 2
    Why do you think you need to save them a separate vectors outside the data.frame? R does not really have a multi-assignment operator. There are some hacky workarounds (https://stackoverflow.com/questions/7519790/assign-multiple-new-variables-on-lhs-in-a-single-line-in-r) but probably best just to avoid in the first place. – MrFlick Mar 30 '18 at 15:39
  • @MrFlick Wow, ok. Yea I'll probably just end up specifying the column vector then. – conv3d Mar 30 '18 at 15:41
  • @MrFlick It is actually convenient though to specify them as individual vector objects because then if you ever need to change any of them you only have to change one part of the code rather than the whole document – conv3d Mar 30 '18 at 15:55
  • 1
    That type of problem is better solved by having a function that takes parameters. Then you can pass whatever you want to the function but the parameter names are always the same. – MrFlick Mar 30 '18 at 15:56
  • 2
    @jchaykow Changing vectors outside of a data frame is a good way to get your columns out of sync with each other. If you do any reordering, subsetting, extending, splitting, etc., it is much easier if everything is in the data frame so the columns stay in sync. And if you use any functions that take a `data` argument (`ggplot`, most modeling functions, ...) you'd have to put your modified columns back in the data frame before using it. – Gregor Thomas Mar 30 '18 at 15:59
  • @Gregor that's true. Thank you. – conv3d Mar 30 '18 at 16:02

1 Answers1

0

Maybe you're looking for 'select'?

library(tidyverse)
iris%>%select(Sepal.Length,Sepal.Width)

This leaves you with a data frame, but if you have some reason for needing another format you could continue with (eg) %>%as.matrix, right?

steveLangsford
  • 646
  • 5
  • 9