简体   繁体   中英

r recode a string variable based on a condition

I know this could be simple, but I can't find the way to solve it. I want to recode a string variable (into the same variable), based on a condition of another variable, but I'm getting an error.

A working example:

    VAR1<-c("SUC1","SUC2","SUC3","SUC4","SUC5","SUC6","SUC7","SUC8","SUC9","SUC10")
    N<-c(356,415,34,1126,21,232,183,53,19,17)
    df<-data.frame(VAR1,N)
    df$VAR1[df$N<=30] <- "OTRO"

Then I received a Warning:

Warning message:
In `[<-.factor`(`*tmp*`, df$N <= 30, value = c(1L, 3L, 4L, 5L, NA,  :
  invalid factor level, NA generated

I know this is not an error, but when I look the result all the categories in VAR1 for wich the N value is below or equal to 30 are setting as NA

What am I doing wrong?

Another twist: If I get the data from aggregate I get the same error, let say:

agg1<-aggregate(VAR3~VAR1,df1,NROW)

and

df<-data.frame(agg1,stringAsFactor=FALSE)

the recode don't seem to work

Any clue?

尝试df<-data.frame(VAR1,N, stringsAsFactors=FALSE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM