简体   繁体   中英

dplyr replace by position in R

The value of the third row of mtcars$mpg is 22.8 .

library(tidyverse)
mtcars$mpg[[3]]

I go ahead and replace this 22.8 with the value 5,555 as shown below. 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.

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 ? 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. 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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