This question already has an answer here:
這個問題在這里已有答案:
根據部分匹配1答案替換整個字符串
Say for example In the data set mtcars, how do i group all the rows containing the string "Merc" and rename them all simply with the string "MERC" like
比如說在數據集mtcars中,我如何對包含字符串“Merc”的所有行進行分組,並簡單地用字符串“MERC”重命名它們
"Merc 240D" -----> "MERC
“Merc 240D”----->“MERC
"Merc 230" -----> "MERC
“Merc 230”----->“MERC
"Merc 280" -----> "MERC
“Merc 280”----->“MERC
"Merc 280C" -----> "MERC
“Merc 280C”----->“MERC
"Merc 450SE" -----> "MERC
“Merc 450SE”----->“MERC
"Merc 450SL" -----> "MERC
“Merc 450SL”----->“MERC
"Merc 450SLC" -----> "MERC
“Merc 450SLC”----->“MERC
Many thanks
1
How about:
mtcars$names <- rownames(mtcars)
mtcars$names <- gsub(".*Merc.*", "MERC", mtcars$names)
mtcars$names
Returns:
[1] "Mazda RX4" "Mazda RX4 Wag" "Datsun 710" "Hornet 4 Drive"
[5] "Hornet Sportabout" "Valiant" "Duster 360" "MERC"
[9] "MERC" "MERC" "MERC" "MERC"
[13] "MERC" "MERC" "Cadillac Fleetwood" "Lincoln Continental"
[17] "Chrysler Imperial" "Fiat 128" "Honda Civic" "Toyota Corolla"
[21] "Toyota Corona" "Dodge Challenger" "AMC Javelin" "Camaro Z28"
[25] "Pontiac Firebird" "Fiat X1-9" "Porsche 914-2" "Lotus Europa"
[29] "Ford Pantera L" "Ferrari Dino" "Maserati Bora" "Volvo 142E"
1
A dplyr
solution:
一個dplyr解決方案:
library(dplyr)
library(tibble)
mtcars %>%
rownames_to_column(var = "make") %>%
mutate(make = gsub("^Merc.+", "MERC", make))
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2018/02/12/7251a6c4290743e5c3e409bbf957e78e.html。