r - replace string in dataframe -
i'm trying replace string in large data.frame. found following solution gsub doesn't preserve original data.frame layout. how can achieve this.
i mean want replace string , don't want change layout of df.
consider example:
test<-data.frame(a=c("a","b","c","d"),b=c("a","e","g","h"),c=c("i","j","k","a")) gsub("a","new",test) thx
you want lapply through data.frame testing character or factor entries , applying gsub appropriately. result list, as.data.frame fixes this.
test$val <- 1:4 # non character/factor variable (test2 <- as.data.frame(lapply(test,function(x) if(is.character(x)|is.factor(x)) gsub("a","new",x) else x))) b c val 1 new new 1 2 b e j 2 3 c g k 3 4 d h new 4 class(test2$val) # see if unchanged [1] "integer"
Comments
Post a Comment