[英]if variable name in data frame column matches names in a vector rename variable
給定一個數據框和一個向量
set.seed(123)
feature <- sample(LETTERS,30,replace = T)
number<-sample(1:100,30, replace = T)
df<-data.frame(feature,number)
rename<-c("N","V","C","E")
我想掃描df$feature
,如果rename
中存儲的字母與df$feature
列中的一個字母匹配,我想將它們重命名為"other"
。
我很確定這一定已經在某個地方得到了回答,不過我已經找了很長時間了。
您可以使用%in%
查找包含rename
的行:
df$feature[df$feature %in% rename] <- "other"
如果df$feature
是一個factor
並且不包含other
級別,則您需要在與以下級別交換之前將other
添加到級別:
levels(df$feature) <- unique(c(levels(df$feature), "other"))
或者您將其轉換為character
:
df$feature <- as.character(df$feature)
使用dplyr
一種選擇:
df %>%
mutate(feature = str_replace(feature, paste(rename, collapse = "|"), "other"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.