Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading