In R-studio , Use a for loop to iterate over all rows of the mtcars dataset to create a car objectfor each row. Use the name of the row, and the values for mpg, cyl, and hp. You canignore the columns not needed for the construction of our car object. After creatingthe car object use the print() function to print it.
The mtcars data set is already integrated in R.
That is what I am using for this question
#Import the pre loaded datasets
data()
#Initialize vectord
cnames <- vector()
carmpg <- vector()
carcyl <- vector()
carhp <- vector()
#Loop mtcars for required car object attributes
"mpg","cyl","hp"
for(i in 1:nrow(mtcars))
{
carmpg <- append(carmpg, mtcars[i,'mpg'])
carcyl <- append(carcyl, mtcars[i,'cyl'])
carhp <- append(carhp, mtcars[i,'hp'])
}
#Loop row names in mtcars for car object attributes
"names"
cnames <- rownames(mtcars)
#Create thr carobject
carobjects <-
list(objcarnames=cnames,objcarcyl=carcyl,objcarmpg=carmpg,objcarhp=carhp)
#Print the car object detaiils
for(object in carobjects)
{
print(paste("Car Names,cyl,mpg,hp
is",carobjects$objcarnames,carobjects$objcarcyl,carobjects$objcarmpg,carobjects$objcarhp))
}
Get Answers For Free
Most questions answered within 1 hours.