简体   繁体   English

如何更改 data.frame 中的单元格值

[英]How to change a cell value in data.frame

Let say I have below data.frame假设我有以下 data.frame

library(dplyr)
DF = data.frame('A' = 1:4, 'B' = letters[1:4])

Now I want to change a specific value -现在我想改变一个特定的值 -

DF[DF[, 'B'] == 'a', 'A'] <- 9999

How can I use dplyr::pipe function to achieve the same?如何使用dplyr::pipe function 来实现相同的目标?

dplyr::mutate() and dplyr::replace() work well for this task. dplyr::mutate()dplyr::replace()非常适合这项任务。

DF %>% 
  mutate(A = replace(A, B == "a", 9999))

mutate() creates a variable A, so after execution, it will overwrite the existing variable A, then replace() replaces the value in A with 9999 whenever B equals "a". mutate()会创建一个变量 A,所以在执行之后,它会覆盖现有的变量 A,然后只要 B 等于“a”, replace()就会将 A 中的值替换为9999

Finally you want to store the result, so the full code looks like this:最后你想存储结果,所以完整的代码如下所示:

DF <- 
 DF %>% 
 mutate(A = replace(A, B == "a", 9999))

Update: in new version of dplyr use mutate(across(...)) rather than mutate_at :更新:在dplyr的新版本中使用mutate(across(...))而不是mutate_at

DF %>%
  mutate(across(A, replace, B == 'a', 9999))

     A B
1 9999 a
2    2 b
3    3 c
4    4 d

Here's how you can accomplish the above using a pipe ( %>% ):以下是使用pipe ( %>% ) 完成上述操作的方法:

DF %>%
  mutate_at("A", ~replace(., B == 'a', 9999))

     A B
1 9999 a
2    2 b
3    3 c
4    4 d

Explanation: you are mutating "at" the variable called "A", so whatever function you call on it will mutate it in place (rather than creating a new variable).解释:你正在“at”改变名为“A”的变量,所以无论你调用什么 function 都会改变它(而不是创建一个新变量)。 You can use ~ instead of the typical syntax function(x) to call an anonymous function that will automatically take .您可以使用~而不是典型的语法function(x)来调用匿名 function ,它将自动获取. as its argument.作为它的论据。 Wherever you place .无论你放在哪里. in the function it will operate on the column "A".在 function 中,它将在“A”列上运行。 You use the replace function on .您使用替换 function on . (column A ), to replace the value 9999 everywhere that the statement B == 'a' is TRUE . (列A ),在语句B == 'a'TRUE的任何地方替换值 9999 。

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

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