Domanda

I'm having some problems with if function in R.

First I tried this:

test<-matrix(10,3,3)
if(test[2,2]==10) {test[2,2]<-5}

Ok, it's doing what I want. So, I will try this:

if(Hylo.Measures[i,3]=="CLc0006x") {Hylo.Measures[i,3]<-"CLc0005x"}

Ops! I got the following message:

Warning message:
In `[<-.factor`(`*tmp*`, iseq, value = "CLc0005x") :
invalid factor level, NA generated

I couldn't figure out what is going on here!

What obvious step am I missing?

È stato utile?

Soluzione

That third column is a factor variable; you might want to check your code to make sure that is what you actually want. Anyway, you can add the level manually if you're sure it's what you want to do. Here's an example of adding a level on iris

R>iris$Species[5] <- "hahah"
Warning message:
In `[<-.factor`(`*tmp*`, 5, value = c(1L, 1L, 1L, 1L, NA, 1L, 1L,  :
  invalid factor level, NA generated

R>levels(iris$Species) <- c(levels(iris$Species), "hahah")
R>iris$Species[5] <- "hahah"
R>iris[5,]
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5            5         3.6          1.4         0.2   hahah

Altri suggerimenti

The problem you are facing is that the character values in your real data.frame are being stored as factors, meaning that the elements of Hylo.Measures[ ,3] (at least) are limited to a discrete set of levels. "CLc0005x is not present in any of your rows, and therefore is not a valid level for that column.

Try executing str(Hylo.Measures), and you will see what I mean.

The easiest way to address this is to build the data.frame without observing factors. For example, if you are using read.table or the like, you can use the argument stringsAsFactors=FALSE, which will ensure that all strings are read in as characters.

I personally set options(stringsAsFactors=FALSE) in my .Rprofile because it typically causes me pain, but this isn't best practice (especially when working in a team) because it can lead to inconsistencies in script behaviour.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top