0

I was wondering which are the posibilities of vectorizing an array of vector using the for-loop.
The general idea is:

  1. Vector names
  2. Vector values
  3. Assign each values from 2 in each 1

As and example I've tried:

Names <- c('Arnold','Jhon' ,'Jim','Jason')`  
Surnames <- c('Palmer','Kramer' ,'Carrey','Momoa')`    
for (Name in Names){
    for (Surname in Surname){
      Name <- Surname
   }
}

What I'm expecting is to create multiple vector named from each individual value form the chracter string Names and each one of this new individual vectors assigned with each surname in Surnames. This would be like:

>Arnold
[1] "Palmer"
>Jhon
[1] "Kramer"

Definitely this isn't working, and I've been searching widebroad in the web, and although there are similar results, there is one that could be, with some modifications obviously, applied to my model. So if you know any other posted questions or any solution I'd be very gladly with you.

  • Can you provide an example of your desired output. Since R functions are already vectorized, you can just use `names(Surnames) <- Names` and `print(Surnames)`. No for-loop needed. – yusuzech Sep 11 '19 at 21:59
  • 2
    This is *not* a good way of thinking about variables and assigning them values in R. For example, what happens if you have two `Arnold`s? It's much better to store `Name` and `Surname` in some form of data structure, e.g. a `list` or a `data.frame`. Extracting entries then comes down to filtering & selecting relevant entries (e.g. through `match`ing entries, or joining with information from another `data.frame`). [Don't use `assign`](https://stackoverflow.com/questions/17559390/why-is-using-assign-bad), as suggested in the answer below. – Maurits Evers Sep 11 '19 at 22:09
  • thanks for the advice, but I only have non repeated values in vector `names` so `assign` function is going to work just fine, but I'll have what you are suggesting in mind in the future if some of my values are repeated. – Paulo Cecco Sep 11 '19 at 22:14

2 Answers2

3

I think you had problems in your loop- I edited so you are looping through a numeric vector. Plus I think the function you were looking for was assign

Names <- c('Arnold','Jhon' ,'Jim','Jason')
Surnames <- c('Palmer','Kramer' ,'Carrey','Momoa')
for( i in 1:length( Names) ){

      assign( Names[i] , Surnames[i] )

}

Arnold
MatthewR
  • 2,660
  • 5
  • 26
  • 37
0

You can create a data.frame and then use the attach() function

Names <- c('Arnold','Jhon' ,'Jim','Jason')  
Surnames <- c('Palmer','Kramer' ,'Carrey','Momoa')

MyData <- rep(0,length(Names))
dim(MyData) <- c(1,length(Names))
MyData <- as.data.frame(MyData)

names(MyData) <- Names
MyData[1,] <- Surnames

attach(MyData) #This is the key
Arnold
Jhon
Jim
Jason
Orlando Sabogal
  • 1,470
  • 7
  • 20