[英]dplyr replace by position in R
The value of the third row of mtcars$mpg
is 22.8
. mtcars$mpg
第三行的mtcars$mpg
22.8
。
library(tidyverse)
mtcars$mpg[[3]]
I go ahead and replace this 22.8
with the value 5,555
as shown below. 我继续将
22.8
替换为值5,555
,如下所示。 It works but not at the third row as I command my computer to do! 它可以工作,但是在我命令计算机执行时却不在第三行! Instead the value shows up at the 22nd row of the
mtcars$mpg
column. 相反,该值显示在
mtcars$mpg
列的第22行。
mtreplace <- mtcars %>% mutate(mpg = replace(mpg, mpg[[3]], 5555))
mtreplace
mtreplace$mpg[[3]]
mtreplace$mpg[[22]]
How do I get this change to occur at precisely the third row of mtcars$mpg
? 我如何使此更改恰好发生在
mtcars$mpg
的第三行? And what went wrong? 怎么了?
该代码应为
mtcars %>% mutate(mpg = replace(mpg, 3, 5555))
I think dplyr is probably overkill, and may not be the best tool for this issue. 我认为dplyr可能是过大了,可能不是解决此问题的最佳工具。 This works fine:
这很好用:
mtcars[3, "mpg"] <- 5555
Also worth bearing in mind that for a numeric vector, you should use single [. 另外要记住,对于数值向量,应使用单[。 The [[ is for lists when you want to get an element and not a range of elements (ie you don't want another list).
[[是用于列表,当您要获取一个元素而不是一系列元素时(即,您不想要另一个列表)。
We can use 我们可以用
library(dplyr)
mtcars %>%
mutate(mpg = case_when(row_number() == 3 ~ 5555, TRUE ~ mpg))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.