user3527451
user3527451

Reputation: 87

R function doesn't do what I want

I don't inderstand why my function doesn't work, can you help me to find my error.

VehiculeFunction <- function(data){
  my.data <- data[data$GAMME =="M1",]
  ma.col = rgb(red = 0.1,blue = 1,green = 0.1, alpha = 0.2)
  X <- my.data$GMF.24
  Y <- my.data$Cout.24
  X11()
  plot(X, Y, pch=20, las = 1, col = ma.col, xlim = c(0, 10), ylim = c(0,10))
  identify(X, Y, labels = my.data$NITG, cex = 0.7)
}

This one works perfectly, and when I add two variables it returns "numeric(0)"

VehiculeFunction <- function(data, x, y){
  my.data <- data[data$GAMME =="M1",]
  ma.col = rgb(red = 0.1,blue = 1,green = 0.1, alpha = 0.2)
  X <- my.data$x
  Y <- my.data$y
  X11()
  plot(X, Y, pch=20, las = 1, col = ma.col, xlim = c(0, 10), ylim = c(0,10))
  identify(X, Y, labels = my.data$NITG, cex = 0.7)
}
VehiculeFunction(data.vehicule, GMF.24, Cout.24)
numeric(0)

thank you Oleg, and if i want to add a condition on another variable of my dataframe, i want to take all the three first of "RANG_NITG_PROJET_K"

my.data1 <- my.data[my.data$RANG_NITG_PROJET_K == 1|2|3,] ? 

but | think it's false because when i do this

my.data1 <- data.vehicule[data.vehicule$RANG_NITG_PROJET_K == 1,]
my.data2 <- data.vehicule[data.vehicule$RANG_NITG_PROJET_K == 2,]
my.data3 <- data.vehicule[data.vehicule$RANG_NITG_PROJET_K == 3,]
my.data <- rbind(my.data1, my.data2, my.data3)

it gives me two different dataframe ?

Upvotes: 0

Views: 56

Answers (1)

Oleg Sklyar
Oleg Sklyar

Reputation: 10082

Try the following. You cannot access my.data columns (or list elements) using the $ operator in this case and you need to pass strings for x and y:

VehiculeFunction <- function(data, x, y, gamme){
  my.data <- data[data$GAMME == gamme,]
  ma.col = rgb(red = 0.1,blue = 1,green = 0.1, alpha = 0.2)
  X <- my.data[[x]] # <- change from $ to [[]]
  Y <- my.data[[y]] # <- change from $ to [[]]
  X11()
  plot(X, Y, pch=20, las = 1, col = ma.col, xlim = c(0, 10), ylim = c(0,10))
  identify(X, Y, labels = my.data$NITG, cex = 0.7)
}

VehiculeFunction(data.vehicule, "GMF.24", "Cout.24", "M1") # <- change to strings

Upvotes: 2

Related Questions