![](/img/trans.png)
[英]Custom function to mutate a new column for row means using starts_with()
[英]Using mutate and starts_with
我想根據它們是否以某個字符串序列開頭來更改某些變量的值。
例子:
df <- data.frame(var1 = c("12345", "12345", "12345", "23456", "23456"))
df %>% mutate(var2 = ifelse(starts_with("123"), "ok", "not ok"))
所有以“123”開頭的值都應更改為“ok”。 如何將starts_with()
與mutate()
結合起來?
謝謝!
starts_with
用於以特定名稱開頭的 select 列。 在這里,您可以使用基礎 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
但是,我們也可以在基礎 R 中執行此操作,而無需ifelse
。
df$var2 <- c('not ok', 'ok')[startsWith(df$var1, '123') + 1]
或者用grepl
df$var2 <- c('not ok', 'ok')[grepl('^123', df$var1) + 1]
數據
startsWith
需要數據是字符,使用stringsAsFactors = FALSE
。
df <- data.frame(var1 = c("12345", "12345", "12345", "23456", "23456"),
stringsAsFactors = FALSE)
我們可以使用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
或者在base R
中使用ifelse
ifelse(grepl('^123', df$var1), 'ok', 'not ok')
#[1] "ok" "ok" "ok" "not ok" "not ok"
df <- data.frame(var1 = c("12345", "12345", "12345", "23456", "23456"),
stringsAsFactors = FALSE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.