簡體   English   中英

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

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

我有以下數據,如果“顏色”中的文本為黃色,我想將計數列中的值更改為負數。 我試過 mutate_if 沒有成功。 如果我想這樣做,我該怎么做:

  1. 用新的負值替換 count 中的值,或
  2. 使用新的負值創建一個名為 Count_final 的新列,以及非黃色條目的相同舊值?

謝謝你。

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"
  )

我們可以多Count 1(保留價值,因為它是)如果Color是不是"Yellow"和-1,如果Color"Yellow" 這可以直接實現

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

或者使用簡單的if_else

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

或者像@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