USER8000
USER8000

Reputation: 3

Having trouble creating a for loop in R

I'm trying to find the mean price for the rear wheel drive car prices in the R pre-specified data frame Cars93. Here is what I tried... I'm getting an unexpected for error.

library(MASS) # has Cars93 data

rearcar <- c()
for(train in 1:nrow(Cars93)){
   if(Cars93$DriveTrain[train] == Rear){
   rearcar <- c(rearcar, train)
   }
}

rearcarprice <- c()
for (train in rearcar){
    rearcarprice <- c(rearcarprice, Cars93[train,6])
}

mean(rearcarprice)

Upvotes: 0

Views: 84

Answers (3)

Gregor Thomas
Gregor Thomas

Reputation: 145755

You shouldn't be using a for loop at all for this.

This gives the subset of the data with "Rear" drivetrain:

Cars93[Cars93$DriveTrain == "Rear", ]

This is the "Price" column for that data subset:

Cars93[Cars93$DriveTrain == "Rear", "Price"]

Thus, this is the average price for that subset:

mean(Cars93[Cars93$DriveTrain == "Rear", "Price"])
# 28.95

All you need is that last line of code.

Upvotes: 2

under_the_sea_salad
under_the_sea_salad

Reputation: 1804

Try correcting your mismatched curly braces as a starting point. And also make sure to put Rear in quotes.

library(MASS)
rearcar<-c()
for(train in 1:nrow(Cars93))
{
  if(Cars93$DriveTrain[train] == 'Rear'){
    rearcar <- c(rearcar, train)
  }
}
rearcarprice <- c()
for (train in rearcar) {
  rearcarprice <- c(rearcarprice, Cars93[train,6])
}
mean(rearcarprice)

Upvotes: 1

russOnXMaps
russOnXMaps

Reputation: 159

Looks like you have a backwards set bracket on the first for loop.

Current

for(train in 1:nrow(Cars93))
    }
    if(Cars93$DriveTrain[train] == Rear){
    rearcar <- c(rearcar, train)
    }}

Try:

for(train in 1:nrow(Cars93))
{
if(Cars93$DriveTrain[train] == Rear){
rearcar <- c(rearcar, train)
}}

Upvotes: 0

Related Questions