5

I'm trying to replace a certain string in a large data.frame. I just found the following solution but gsub doesn't preserve the original data.frame layout. How can I achieve this.

I mean I want to replace a string and don't want to change the layout of the df.

Consider this 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

2 Answers 2

14

You will want to lapply through your data.frame testing for character or factor entries and then applying gsub appropriately. The result will be a list, but as.data.frame fixes this.

test$val <- 1:4 # a 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)))
    a   b   c val
1 new new   i   1
2   b   e   j   2
3   c   g   k   3
4   d   h new   4
class(test2$val) # to see if it is unchanged
[1] "integer"
2
  • why did you wrap the whole expression in brackets? Commented Jan 29, 2014 at 9:18
  • 3
    @RichardSmith That makes the expression return its result visibly to the console. Assignment is normally returned invisibly.
    – James
    Commented Jan 29, 2014 at 9:58
6
as.data.frame(sapply(test, function(x) gsub("a", "new", x)))
1
  • thanks, but that gives me a character matrix, my df has numerical values too, then I run into problems when processing the data further
    – rainer
    Commented May 14, 2013 at 10:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.