Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

How to create a function with already written for-loop to automatically create vectors in r environment

$
0
0

I have a df with fixed columns and unfixed row number. I created empty vectors and populate R commands to create vectors on its own once I use eval(parse(text = someVector)). What I did with for-loop works, but I would like to turn it into a function and/or use *apply() and I don't know how to do that. I would very much like to upgrade my programming skills. I would like to be able to choose the variables by name or position and always go through every row.

working with the reprex, I expect 30 vectors created in the working environment - for every car model for the specified column separate vector to store the value of that column for this row/carmodel and 6 more vectors that store the R commands.

for example one of the vectors should look like this: cyl_MazdaRX4Wag <- 6

# df
df <- mtcars[1:5,]  
df$carmodel <- gsub("[[:space:]]", "", rownames(df))


# create empty vectors to store R command 
carmodel <- c() 
mpg <- c() 
cyl <- c() 
hp <- c() 
gear <- c() 
carb <- c()

# loop through every row to create an R command
for(i in 1:nrow(df)){
     carmodel[i] <-  paste0("carmodel_", df$carmodel[i] , "<- ", "'", df$carmodel[i], "'",";")
     mpg[i] <-  paste0("mpg_", df$carmodel[i],  "<- ", df$mpg[i], ";")   
     cyl[i] <-  paste0("cyl_", df$carmodel[i],  "<- ", df$cyl[i], ";")   
     hp[i] <-  paste0("hp_", df$carmodel[i],  "<- ", df$hp[i], ";") 
     gear[i] <-  paste0("gear_", df$carmodel[i],  "<- ", df$gear[i], ";")  
     carb[i] <-  paste0("carb_", df$carmodel[i],  "<- ", df$carb[i], ";")  
}
# collapse the vectors in one string
carmodel <- paste(carmodel, collapse = "") 
mpg <- paste(mpg, collapse = "")
cyl <- paste(cyl, collapse = "")
hp <- paste(hp, collapse = "") 
gear <- paste(gear, collapse = "") 
carb <- paste(carb, collapse = "")

# execute R command
eval(parse(text = carmodel)) 
eval(parse(text = mpg)) 
eval(parse(text = cyl)) 
eval(parse(text = hp)) 

# delete vectors that store the R commands
rm(list = c("carmodel","mpg","cyl", "hp","gear","carb"))
eval(parse(text = gear)) 
eval(parse(text = carb))

Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>