Search code examples
rr-factor

How to make a factor a numeric value?


This is my second time posting, so I hope I get the "reproducible example" thing right.

Here is the error,

Error in if ((sound[i, 3] < -10 & sound[min(81, i + 1), 3] > -10) | (sound[i,  : 
  missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In Ops.factor(sound[i, 3], -10) : < not meaningful for factors
2: In Ops.factor(sound[min(81, i + 1), 3], -10) :
  > not meaningful for factors
3: In Ops.factor(sound[i, 3], -10) : > not meaningful for factors
4: In Ops.factor(sound[min(81, i + 1), 3], -10) :
  < not meaningful for factors

Here is the code,

> for(i in 3:length(sound[,2])){
+ if(sound[i,3]==-10){
+ soundout[m,7]=sound[i,2]
+ m=m+1}
+ if((sound[i,3]< -10&sound[min(81,i+1),3]>-10)|(sound[i,3]>-10&sound[min(81,i+1),3]< -10)){
+ soundout[m,7]=(10-sound[i,3])*(sound[i+1,2]-sound[i,2])/(sound[i+1,3]-sound[i,3])+sound[i,2]
+ m=m+1}}

Can someone please tell me how to make the factor sound[1,3] a numeric value? Thank you,


Solution

  • For the example to be reproducible, we need both code and data. Right now, I can't take your code and run it on my machine and generate the same error you see (which is what is meant by having a reproducible example). You don't need to give us your entire dataset, just a similar simple example with 5-10 rows and only the necessary columns so that we can see what's going on.

    Senor O is absolutely right that the problem is that sound[, 3] is a factor. Before running the code you posted, run this:

    colnames(sound) <- sound[1, ]
    sound <- sound[-1:2, ]
    
    sound[, 2] <- as.numeric(as.character(sound[, 2]))
    sound[, 3] <- as.numeric(as.character(sound[, 3]))
    sound[, 7] <- as.numeric(as.character(sound[, 7]))
    

    That will turn the data you want to do arithmetic operations on into numbers. It seems like you have headers or data you don't want to use in rows 1 and 2, so I only coerced rows three and on for the columns that you use in your loop.

    Edit: MrFlick is also right that it's likely possible to fix this up-front when you read the data, but without knowing what kind of file you're reading and how you're doing that we can't necessarily say what you should do. If you're reading something like a CSV file from disk, though, set as.is = TRUE and that will bring in numbers as numeric, characters as characters, etc.