I have one question which is probably easy for a lot of you. I would like to write a function which will do the calculations based on condition in selected column. It will be easier to show you an example:
con <- c("A", "B", "B", "C", "C", "A", "D", "A", "B", "D", "D", "D")
value <- c(1, 3, 2, 1, 1, 1, 2, 1, 2, 3, 3, 2)
dat <- data.frame(con, value)
head(dat)
So one possibility would be to do this in this simple way:
dat$new <- ifelse(dat$con == "A", dat$value*10,
ifelse(dat$con == "B", dat$value*100, dat$value*1000))
head(dat)
But, my question is how would the function look like? I tried something like this, but it is not working. Can someone help me with explanation what is missing and wrong?
calc <- function(dat) {
if(dat[, con] == "A") {
new <- dat$value*10
}
if(dat[, con] == "B") {
new <- dat$value*100
} else {
new <- dat$value*1000
}
}
Aucun commentaire:
Enregistrer un commentaire