0

I would like to create a vector from each column of mtcars data frame. I need two solutions. First one should be done in loop and if it's possible the other one without a loop.

The desired output should be like that:

vec_1 <- mtcars[,1]
vec_2 <- mtcars[,2]

etc...

I tried to create a loop but I failed. Can you tell me what is wrong with that loop ?

vec <- c()
for (i in 1:2){
  assign(paste("vec",i,sep="_" <- mtcars[,i][!is.na(mtcars[,i])]
}

I need to remove possible NAs from my data that's why I put it in the example.

Shaxi Liver
  • 1,052
  • 3
  • 25
  • 47
  • 2
    Why do you want to do this... – MichaelChirico Oct 23 '15 at 14:19
  • 1
    The answer is `attach` but chances are close to 0 that you should actually do this. – MichaelChirico Oct 23 '15 at 14:20
  • The each vector will be used for creating another loop where I will extract `strings` from my main data frame and store them as separate data frames. I mean the strings stored in `vec` will be used to extract rows from big data frame. – Shaxi Liver Oct 23 '15 at 14:20
  • I think what they are getting at is the fact that you can call each column as a vector from the data frame without explicitly generating objects in R. – Badger Oct 23 '15 at 14:21
  • And why do you want to do that? – MichaelChirico Oct 23 '15 at 14:22
  • To avoid creating multiple loops at the same time. As you see I am not so good with looping. The whole idea is to create plots based on selected rows from different data frames and export them as different pdf files which in my opinion needs multiple loops. – Shaxi Liver Oct 23 '15 at 14:23
  • It is connected to thread I have created before: http://stackoverflow.com/questions/33260239/writing-a-loop-to-create-ggplot-figures-with-different-data-sources-and-titles – Shaxi Liver Oct 23 '15 at 14:26
  • I think you are looking to do this: http://stackoverflow.com/questions/11346880/r-plot-multiple-box-plots-using-columns-from-data-frame Within the loop write your pdf function with an iterative naming convention and you should be good to go. This may also be of use: http://stackoverflow.com/questions/19146665/how-subset-a-data-frame-by-a-factor-and-repeat-a-plot-for-each-subset – Badger Oct 23 '15 at 14:28

1 Answers1

1

Your loop is missing a few brackets and you should assign the vector to the global environment of your R session like so:

for (i in 1:2) {
  assign(sprintf("vec_%d", i), mtcars[!is.na(mtcars[[i]]), i], envir = .GlobalEnv)
}

It is not possible to get the desired result without a loop.

mjkallen
  • 468
  • 3
  • 12