比如说在数据集mtcars中,我如何对包含字符串" Merc"的所有行进行分组。并简单地用字符串" MERC"重命名它们。喜欢
" Merc 240D" -----> " MERC
" Merc 230" -----> " MERC
" Merc 280" -----> " MERC
" Merc 280C" -----> " MERC
" Merc 450SE" -----> " MERC
" Merc 450SL" -----> " MERC
" Merc 450SLC" -----> " MERC
非常感谢
答案 0 :(得分:1)
怎么样:
mtcars$names <- rownames(mtcars)
mtcars$names <- gsub(".*Merc.*", "MERC", mtcars$names)
mtcars$names
返回:
[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 :(得分:1)
dplyr
解决方案:
library(dplyr)
library(tibble)
mtcars %>%
rownames_to_column(var = "make") %>%
mutate(make = gsub("^Merc.+", "MERC", make))