简体   繁体   English

改变由数字指定的特定行的 tibble

[英]mutate tibble for particular rows specified by a numbers

Trying to find dplyr canonical way to mutate a tibble by row number.试图找到dplyr规范的方法来mutate一个tibble的行号。
I went through many Stack Overflow questions and GH issues, functions like row_number , if_else , case_when , but it is still not clear what is the proper way to achieve the following.我经历了许多堆栈溢出问题和 GH 问题,诸如row_numberif_elsecase_when ,但仍然不清楚实现以下目标的正确方法是什么。

Minimal example: having a data.frame, I would like to update one of its columns to a particular value (here NA ) for particular rows by providing row indices (here rows 2 and 4).最小示例:有一个 data.frame,我想通过提供行索引(此处为第 2 行和第 4 行)将其列之一更新为特定行的特定值(此处为NA )。
Column to update doesn't have to be parametrized, but only row numbers.要更新的列不必参数化,而只需参数化行号。
Below base R to achieve the following.在基础 R 下实现以下功能。

DF = data.frame(x=5:1)
idx = c(2L, 4L)
DF[idx, "x"] = NA_integer_
DF
#   x
#1  5
#2 NA
#3  3
#4 NA
#5  1

Based on @camille feedback and the consent by other commentors the most tidyverse-like code is mutate(x = ifelse(row_number() %in% idx, NA_integer_, x)) .根据@camille 的反馈和其他评论者的同意,最类似于 tidyverse 的代码是mutate(x = ifelse(row_number() %in% idx, NA_integer_, x))

BTW.顺便提一句。 It is better to use <- instead of = assignments, and avoid usage capital letters in the names of objects.最好使用<-而不是=赋值,并避免在对象名称中使用大写字母。 For more information please see The tidyverse style guide有关更多信息,请参阅tidyverse 风格指南

So the full code:所以完整的代码:

library(dplyr)
df <- data.frame(x = 5:1)
idx <- c(2L, 4L)
df %>% mutate(x = ifelse(row_number() %in% idx, NA_integer_, x))

#   x
#1  5
#2 NA
#3  3
#4 NA
#5  1

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

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