简体   繁体   English

根据该行中另一个单元格的值更改 dataframe 单元格中的值 (R)

[英]Changing a value in a dataframe cell based on the value of another cell in that row (R)

Let's say I have a data frame假设我有一个数据框

Name | Cat_1 | Val 2
---------------------
A    | red   | 0
---------------------
B    | blue  | 1
---------------------
C    | green | 2
---------------------

I want to change the value of the Val 2 column for the row that meets a given condition in a different cell.我想更改不同单元格中满足给定条件的行的 Val 2 列的值。

For example, how would I change the Val_2 value for a row to 10 if its Cat_1 is equal to "blue"?例如,如果某行的 Cat_1 等于“blue”,我如何将其 Val_2 值更改为 10? I don't want to use an if statement or for loop, I feel like there is a way to get this using dplyr or something (I am using R FYI).我不想使用 if 语句或 for 循环,我觉得有一种方法可以使用 dplyr 或其他东西(我正在使用 R 仅供参考)。 Let me know if you can help!如果你能帮忙,请告诉我! Thank you!谢谢!

You may try case_when :您可以尝试case_when

library(dplyr)

df %>%
  mutate(Val_2 = 
     case_when(
       Cat_1 == ”blue” ~ 10,
       Cat_1 == ”green” ~ 5,
       Cat_1 == ”red” ~ 3)
    )

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

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