【问题标题】:R - Change values in one column if conditions in other columns are metR - 如果满足其他列中的条件,则更改一列中的值
【发布时间】:2018-12-13 00:27:51
【问题描述】:

我有一个矩阵,如下所示:

Area_Code <- as.character(c("Red","Yellow","Orange","Orange","Orange"))
Garden_Size <- as.numeric(c(75,100,50,170,105))
Property_Type <- as.character(c("House","Flat","Bungalow","House","House"))
House_Price <- as.numeric(c(110000,120000,355000,495000,150000))
Matrix <- cbind(Area_Code,Garden_Size,Property_Type,House_Price)

我希望能够设置变量,例如; Area_Code 必须为橙色 花园大小必须 > 100 属性类型必须为“房屋”

然后,如果每行都满足这些特定条件,我想将 House_Price 变量增加一些量 - 对于此示例,假设为 10%。

我希望将生成的更改保存为新矩阵,以便我拥有旧矩阵和新更新矩阵的副本。

因此,对于这个特定示例,我希望代码产生新矩阵与旧矩阵相同的结果,除了底部两行(与上面设置的参数匹配)的价格增加了 10%。

提前感谢您的任何回答!

【问题讨论】:

标签: r


【解决方案1】:

您的变量是各种类,因此数据框比矩阵更有意义。

Area_Code <- c("Red","Yellow","Orange","Orange","Orange")
Garden_Size <- c(75,100,50,170,105)
Property_Type <- c("House","Flat","Bungalow","House","House")
House_Price <- c(110000,120000,355000,495000,150000)
df <- data.frame(Area_Code, Garden_Size, Property_Type, House_Price)

在这里,我使用dplyr 检查条件,如果满足,则将房价增加 10%。否则,没有变化。

df2 <- df %>% 
  mutate(House_Price = ifelse(Property_Type == "House" &
                              Area_Code == "Orange" &
                              Garden_Size > 100, 
                              House_Price * 1.1, 
                              House_Price))

最后,比较一下dfdf2

df

#   Area_Code Garden_Size Property_Type House_Price
# 1       Red          75         House      110000
# 2    Yellow         100          Flat      120000
# 3    Orange          50      Bungalow      355000
# 4    Orange         170         House      495000
# 5    Orange         105         House      150000

df2

#   Area_Code Garden_Size Property_Type House_Price
# 1       Red          75         House      110000
# 2    Yellow         100          Flat      120000
# 3    Orange          50      Bungalow      355000
# 4    Orange         170         House      544500
# 5    Orange         105         House      165000

【讨论】:

  • 完美回应。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
  • 2021-10-04
  • 2022-12-09
相关资源
最近更新 更多