dimanche 8 novembre 2020

How do I write a function in r to do cacluations on a record?

In C# I am used to the concept of a data set and a current record. It would be easy for me to write a complicated calc-price function with conditions on the current record.

I am having trouble understanding how to do this in r.

I tried the following

   train <- read.csv("Train.csv" )
   df <- as.data.frame.matrix(train)
   v = c(  df$Fuel.Type ,df$No.Gears)
   names(v ) <- c( "FuelType" ,"NoGears")
   df$FEType = FEType( v)

Where the my function is defined as

FEType <- function(v    ){
  ret="Low"
  if (v["FuelType"]=='G') {
    ret ="High"
  }
  return(ret)
}

This is not working how I expected and when I examine v I see that it contains aggregate totals rather than the current row I expected.

Where am I going wrong?

In the question here I see some hints in the last paragraph.

To reproduce the problem, indicating what I want to do, I have

IsPretty <-function(PetalWidth){
  if (PetalWidth  >0.3) return("Y")
  return("N")
}

#plot(cars)
df <- iris
df$Pretty = IsPretty(df$Petal.Width)
    

This gives the error

the condition has length > 1 and only the first element will be used

Which led me to look into vectors. But I am not confident that is the right direction.

[Update]

I am used to thinking of tables and current records. Thus I was thinking that

df$Pretty = IsPretty(df$Petal.Width)

would have the effect of adding a column to my data frame with the calculated isPretty property

Why can I not include if conditions in my calculation?

Aucun commentaire:

Enregistrer un commentaire