2

after a lot of trial/error and the search function I am still somewhat clueless about an I-thought-simple-thing (as always, hrmpf):

I have a column in a data frame x$question and within that column, there is an expression 'A/V' every once in a while, and I simply want it to be changed to 'A / B'.

I tried a little here and there, and thought this should work:

 x$question[agrep('A/V',x$question)]<-'A / B'

but I get the error:

In `[<-.factor`(`*tmp*`, agrep('A/V',  :
invalid factor level, NAs generated    

or I could do this

agrep('A/V','A / B', x$question).

But here I get the error:

Error in .amatch_bounds(max.distance) : 
match distance components must be non-negative

Since I am quite out of ideas, I would be very thankful, if you had a suggestions, or maybe an even simpler way of replacing a string with another string.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Al_
  • 89
  • 1
  • 7
  • 2
    Your data is a `factor`, either convert to `character` or modify the `levels` instead. Provide an example and I will demonstrate how. – James Aug 06 '13 at 14:39
  • Hi James, and thanks! - I knew it, damn factor****. Shouldn't `levels(x$question["A/V"])<-"A / B"` work, though? (which it doesn't). Am I still missing something? - I'll upload a small file with an example, just a sec – Al_ Aug 06 '13 at 14:46

1 Answers1

1

Does this work?

 gsub("A/V","A/B",x$question)

Example:

x<-c("A/V", "A/V", "A/V")
x<-gsub("A/V","A/B",x)
>x
[1] "A/B" "A/B" "A/B"

Note: You can use ifelse for that too.

> ifelse(x=="A/B","A/V",x)
[1] "A/V" "A/V" "A/V"
Metrics
  • 15,172
  • 7
  • 54
  • 83
  • Well, it kind of does and does not - it puts out the levels (with the now correctly changed expression), but does not change the data! – Al_ Aug 06 '13 at 14:50
  • Just assigned it to column you want to replace like `x<-gsub("A/V","A/B",x)` and it will replace all. – Metrics Aug 06 '13 at 14:52