Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using apply with assign in R

Tags:

loops

r

apply

Consider the following example:

Vars <- c("car","bike","lorry")
Dat <- c(10,20,22)

for (i in 1:length(Vars)){
  assign(Vars[i],Dat[i])
}

Here, I would like to generate three variables in the workspace named according to the entries in Vars and the values in Dat. At the moment I am using a loop, but I have been trying to remove the loop by using apply, how would be the best way of doing this?

like image 741
KatyB Avatar asked Apr 29 '13 10:04

KatyB


People also ask

What does assign () do in R?

In R programming, assign() method is used to assign the value to a variable in an environment.

How do you assign a value in R studio?

Use variable <- value to assign a value to a variable in order to record it in memory. Objects are created on demand whenever a value is assigned to them. The function dim gives the dimensions of a data frame. Use object[x, y] to select a single element from a data frame.

How does Sapply work in R?

sapply() function takes list, vector or data frame as input and gives output in vector or matrix. It is useful for operations on list objects and returns a list object of same length of original set. Sapply function in R does the same job as lapply() function but returns a vector.


2 Answers

This is a great example of when to use a for loop instead of an apply.
The best solution is to leave it as it is.

if you really want to use an *ply loop, use mapply

 mapply(assign, Vars, Dat, MoreArgs=list(envir=parent.frame()))
like image 193
Ricardo Saporta Avatar answered Sep 21 '22 14:09

Ricardo Saporta


You can also use attach for example:

attach(as.list(setNames(Dat,Vars)))
like image 24
user1609452 Avatar answered Sep 23 '22 14:09

user1609452