简体   繁体   English

使用 mutate 和 starts_with

[英]Using mutate and starts_with

I would like to change the value of certain variables depending on whether they start with a certain string-sequence.我想根据它们是否以某个字符串序列开头来更改某些变量的值。

Example:例子:

df <- data.frame(var1 = c("12345", "12345", "12345", "23456", "23456"))
df %>% mutate(var2 = ifelse(starts_with("123"), "ok", "not ok"))

All values starting with "123" should be changed into "ok".所有以“123”开头的值都应更改为“ok”。 How can I combine starts_with() with mutate() ?如何将starts_with()mutate()结合起来?

Thanks!谢谢!

starts_with is used to select columns which start with a particular name. starts_with用于以特定名称开头的 select 列。 Here you can use base R startsWith instead.在这里,您可以使用基础 R startsWith代替。

library(dplyr)
df %>% mutate(var2 = ifelse(startsWith(var1, "123"), "ok", "not ok"))

#   var1   var2
#1 12345     ok
#2 12345     ok
#3 12345     ok
#4 23456 not ok
#5 23456 not ok

However, we can also do this in base R and without ifelse .但是,我们也可以在基础 R 中执行此操作,而无需ifelse

df$var2 <- c('not ok', 'ok')[startsWith(df$var1, '123') + 1]

Or with grepl或者用grepl

df$var2 <- c('not ok', 'ok')[grepl('^123', df$var1) + 1]

data数据

startsWith need data to be character, use stringsAsFactors = FALSE . startsWith需要数据是字符,使用stringsAsFactors = FALSE

df <- data.frame(var1 = c("12345", "12345", "12345", "23456", "23456"), 
      stringsAsFactors = FALSE)

We can use case_when我们可以使用case_when

library(dplyr)
library(stringr)
df %>% 
  mutate(var2 = case_when(str_detect(var1, '^123') ~ 'ok',
                TRUE ~ 'not ok'))
#   var1   var2
#1 12345     ok
#2 12345     ok
#3 12345     ok
#4 23456 not ok
#5 23456 not ok

Or with ifelse in base R或者在base R中使用ifelse

ifelse(grepl('^123', df$var1), 'ok', 'not ok')
#[1] "ok"     "ok"     "ok"     "not ok" "not ok"

data数据

df <- data.frame(var1 = c("12345", "12345", "12345", "23456", "23456"), 
      stringsAsFactors = FALSE)

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

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