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?
In R programming, assign() method is used to assign the value to a variable in an environment.
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.
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.
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()))
You can also use attach
for example:
attach(as.list(setNames(Dat,Vars)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With