我有一個資料集,我需要將不包含文本“INV”的任何設備的值更改為 0。
Device Value
RGM 4279
INV A1 727
INV A2 3731
POA 73974
我認為這樣的事情會起作用,但它不會。
if (grepl(!"INV", df$Device, fixed = TRUE) {
df$Value <- 0
}
有任何想法嗎?
uj5u.com熱心網友回復:
基礎解決方案
要按照您最初打算的方式修改內容,只需下標df$Value以定位不匹配項,然后使用<- 0以下內容覆寫:
df$Value[!grepl("INV", df$Device, fixed = TRUE)] <- 0
整潔的替代品
或者,如果你想在tidyverse約定范圍內作業,這應該可以解決dplyr:
library(dplyr)
df <- df %>%
# Mutate the column as a whole.
mutate(
Value = if_else(
# Determine which values in the column do NOT (!) match the regex.
!grepl("INV", Value, fixed = TRUE),
# Overwrite any matches with 0; otherwise keep the original value.
0, Value
)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/403831.html
標籤:
上一篇:加入資料框,保留列名
