英文:
Error on creating conditional column in R
问题
谢谢您的友善回复。我有一个数据框,我需要根据另一列的值应用公式来计算列的值:
data <- data.frame(figure = c("square","square","circle","square","circle"),
diameter =c(NA,NA,21,NA,12),
side=c(32,27,NA,51,NA))
我需要根据正方形或圆形的公式计算面积(正方形=边长边长,圆形=π(直径/2)^2)并将结果存储在一个新列中:
data$area <- 0
data$area[data$figure == "square"] <- data$side*data$side
data$area[data$figure == "circle"] <- pi*(data$diameter/2)^2
但是,当我这样计算时,我得到了最后一个公式和以下错误:
替换的项数不是替换的长度的倍数。
我认为这可能与括号中的列选择有关。任何帮助将不胜感激。
英文:
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.
答案1
得分: 1
以下是翻译好的部分:
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
```R
> 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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论