简体   繁体   English

根据r中的另一列更改一列的值

[英]Changing the value of one column based on another in r

I have the following data, and I want to change the values in the count column to negative if the text in 'Color' is Yellow.我有以下数据,如果“颜色”中的文本为黄色,我想将计数列中的值更改为负数。 I tried mutate_if with no success.我试过 mutate_if 没有成功。 How can I go about doing so if I want to:如果我想这样做,我该怎么做:

  1. Replace the values in count with the new negative values, or用新的负值替换 count 中的值,或
  2. Create a new column with the name Count_final with new negative values, as well as the same old values for the entries that are not yellow?使用新的负值创建一个名为 Count_final 的新列,以及非黄色条目的相同旧值?

Thank you.谢谢你。

data <- tibble::tribble(
    ~Color,    ~Item, ~Count,       ~Year,
    "Blue",    "Bag",     50, "2009-2011",
    "Blue", "Wallet",     60, "2009-2011",
   "Green",  "Shoes",     80, "2009-2011",
   "Green",  "Shirt",     90, "2009-2011",
  "Yellow", "Flower",     20, "2009-2011",
  "Yellow",   "Bees",     30, "2009-2011",
    "Blue",    "Bag",     50, "2009-2011",
    "Blue", "Wallet",     60, "2009-2011",
   "Green",  "Shoes",     90, "2009-2011",
   "Green",  "Shirt",     20, "2009-2011",
  "Yellow", "Flower",     10, "2009-2011",
  "Yellow",   "Bees",      5, "2009-2011"
  )

We can multiply Count with 1 (to keep the value as it is) if Color is not "Yellow" and -1 if Color is "Yellow" .我们可以多Count 1(保留价值,因为它是)如果Color是不是"Yellow"和-1,如果Color"Yellow" This can be achieved directly with这可以直接实现

data$Count_final <- with(data, Count * c(1, -1)[(Color == "Yellow") + 1])

# A tibble: 12 x 5
#   Color  Item   Count Year      Count_final
#   <chr>  <chr>  <dbl> <chr>           <dbl>
# 1 Blue   Bag       50 2009-2011          50
# 2 Blue   Wallet    60 2009-2011          60
# 3 Green  Shoes     80 2009-2011          80
# 4 Green  Shirt     90 2009-2011          90
# 5 Yellow Flower    20 2009-2011         -20
# 6 Yellow Bees      30 2009-2011         -30
# 7 Blue   Bag       50 2009-2011          50
# 8 Blue   Wallet    60 2009-2011          60
# 9 Green  Shoes     90 2009-2011          90
#10 Green  Shirt     20 2009-2011          20
#11 Yellow Flower    10 2009-2011         -10
#12 Yellow Bees       5 2009-2011          -5

Or with simple if_else或者使用简单的if_else

library(dplyr)
data %>% mutate(Count_final = Count * if_else(Color == "Yellow", -1, 1))

Or as @Kent Johnson suggested -或者像@Kent Johnson 建议的那样 -

data %>% mutate(Count_final = if_else(Color=='Yellow', -Count, Count))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM