简体   繁体   中英

rename object created <-as.character

library(vegan)
data(dune)
dune.spec<-data.frame(Species=colnames(dune))
species<-as.character(dune.spec$Species)


levels(species)[levels(species)=="Achimill"] <- "test"
library(dplyr)
species<-rename(species, replace = c("Achimill" = "test"))

I'd like to rename a specific name. For example "Achimill" to "test". Seems like such a simple thing to do but I can't find a method that works. Neither levels of rename function works.

library(vegan)
data(dune)
dune.spec = data.frame(Species = colnames(dune))
species = as.character(dune.spec$Species)

species is character , that's why you can't get levels to work, as it operates on factor

class(species)
#[1] "character"

Substitute the way you want using methods available for character , such as base::gsub

species = gsub("Achimill", "test", species)

Alternatively, since it seems you may actually be trying to use the factors, operate on a factor using appropriate methods

dune.spec$Species = factor(dune.spec$Species, labels = gsub("Achimill", "test", levels(dune.spec$Species)))
dune.spec$Species
# [1] test     Agrostol Airaprae Alopgeni Anthodor Bellpere Bromhord Chenalbu
# [9] Cirsarve Comapalu Eleopalu Elymrepe Empenigr Hyporadi Juncarti Juncbufo
#[17] Lolipere Planlanc Poaprat  Poatriv  Ranuflam Rumeacet Sagiproc Salirepe
#[25] Scorautu Trifprat Trifrepe Vicilath Bracruta Callcusp
#30 Levels: test Agrostol Airaprae Alopgeni Anthodor Bellpere ... Vicilath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM