nhedzll
nhedzll

Reputation: 35

Error on creating conditional column in R

Thank you for your kind responses. I have a dataframe and I need to apply a formula over a columns depending of the value of other column:

data <- data.frame(figure = c("square","square","circle","square","circle"),
                   diameter =c(NA,NA,21,NA,12),
                   side=c(32,27,NA,51,NA))

What I need is to calculate the area according the square or circle formula (square = side * side, circle= pi*(diameter/2)^2) in a new column:

data$area <- 0
data$area[data$figure == "square"] <- data$side*data$side
data$area[data$figure == "circle"] <- pi*(data$diameter/2)^2

But when I calculate this way, I get the last formula and the following error:

The number of items to replace is not a multiple of the length of the replacement.

I suposse this could be related with column selection in brackets. Any help will be appreciated.

Upvotes: 1

Views: 28

Answers (1)

akrun
akrun

Reputation: 887691

We could use ifelse

data$area <- with(data, ifelse(figure == "square", side^2, pi*(diameter/2)^2))

The lhs and rhs should have the same length. In the OP's code, the lhs is of different length than the rhs (i.e. full column values are used in rhs) i.e.

data$area[data$figure == "square"] <- (data$side*data$side)[data$figure == "square"]
data$area[data$figure == "circle"] <- (pi*(data$diameter/2)^2)[data$figure == "circle"]

-output

> data
  figure diameter side      area
1 square       NA   32 1024.0000
2 square       NA   27  729.0000
3 circle       21   NA  346.3606
4 square       NA   51 2601.0000
5 circle       12   NA  113.0973

Upvotes: 1

Related Questions