Oriol Prat
Oriol Prat

Reputation: 1047

replace a character element of a data frame

I have a data frame and some character misread,

example1
1         SABRINA MOCKENHAUPT
2             IRINA MIKITENKO
3         MARILSON DOS SANTOS
4                   RYAN HALL
5                 TIKI GELANA
6            KENTARO NAKAMOTO
7               JAOUAD GHARIB
8                   S…REN KAH
9            CONSTANTINA DITA

and I would want to replace some element. For example, replace eighth element exemple1$exemple1[[8]]<-"SÖREN KAH". But it shows me this error

In `[[<-.factor`(`*tmp*`, 8, value = c(57L, 29L, 41L, 54L, 65L,  :invalid factor level, NA generated

Upvotes: 0

Views: 133

Answers (1)

ricardo
ricardo

Reputation: 8435

You have not provided a reproducible example, so i'm guessing a little: but it seems that the problem is that example1 is made up of factors.

Here's a basic guess at example1

example1 <- as.factor(LETTERS[1:9])

when you print your factor1 you probably see something like the following:

R> example1
[1] A B C D E F G H I
Levels: A B C D E F G H I

Now if we try and replace any item with a non-factor (something not listed in levels above), we will get the following error (which is similar to yours):

R> example1[8] <- "KK"
Warning message:
In `[<-.factor`(`*tmp*`, 8, value = "KK") :
  invalid factor level, NA generated

but note that you could make a substitution of one listed factor for another -- meaning that example1[8] <- "A" is valid.

My guess is that you don't want factors -- you want characters. So you need to coerce example1 to character. Do this as follows

R> example1.ch <- as.character(example1)

No your substitution will work:

R> example1.ch[8] <- 'kk'
R> example1.ch
[1] "A"  "B"  "C"  "D"  "E"  "F"  "G"  "kk" "I"

In general, you can use the command str() to learn about what your data object is comprised of -- which will help when you get odd errors like this one.

R> str(example1)
 Factor w/ 9 levels "A","B","C","D",..: 1 2 3 4 5 6 7 1 9

Upvotes: 1

Related Questions