简体   繁体   中英

Problems with conditioning a column's value from another column's RANGE

I assume that this was asked already, but I was searching a lot and I haven't found any solution yet. I do have the following data.frame

date     OCC2010          
 1992-1    8460               
 1992-1    7390               
 1992-1    9999               
 1992-2    244                
 1992-2    2349               
 1992-2    0592               

What I wanna do is actually pretty simple. I would like to allocate the value 3 to column SKILLOCC , if a row in column OCC2010 is within range of certain numbers, eg 8460:9999 , as specified in the following table.

date     OCC2010          SKILLOCC
 1992-1    8460               4
 1992-1    7390               0
 1992-1    9999               4
 1992-2    244                0
 1992-2    2349               0
 1992-2    0592               0
df$SKILLEDOCC <- 0
df[df$OCC2010 == 8460:9999,]
df[df$OCC2010 == 8460:9999,]$SKILLEDOCC <- "3"

I used that code already for one value or a value < x and it worked. If I try it with a range, the error

> is not a multiple of the length of the connecting object occurs. Does anyone have an idea how to fix that? Or is there another smarter way?

Many thanks in advance

Xx Freddy

It would be %in% as == is elementwise comparison and works only in two cases - 1) when both the lengths are the same, 2) when the rhs length is 1 so that it recycles.

df$SKILLEDOCC[df$OCC2010 %in% 8460:9999] <- 3

Also, it is better to do the assignment on a vector ( df$SKILLEDOC ), instead of the data.frame indexing

Or as @thelatemail suggested a comparison operation may be more efficient

df$SKILLEDOCC[df$OCC2010 >= 8460 & df$OCC2010 <= 9999] <- 3

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