-3

I have a data frame df1 such that:

group=c(0,5,3,0,5,3)
year=c("2001","2002","2003", "2010", "2012", "2013")
items=c(12, 10, 15, 5, 10, 7)
df1=data.frame(group, year, items)

I want to create a new column where I assign a value to one year and while leaving the rest at 0. For example, I want it to look like this:

  group year items new  
1     0 2001    12   1
2     5 2002    10   0  
3     3 2003    15   0
4     0 2010     5   0
5     5 2012    10   0
6     3 2013     7   0

Thanks!

shrimp32
  • 147
  • 1
  • 3
  • 9

2 Answers2

4

In the absence of other requirements, I would use:

df1$new <- ifelse(year == 2001, 1, 0)
Benjamin
  • 16,897
  • 6
  • 45
  • 65
  • 1
    @akrun You should have kept that as an answer, it's pretty clever. – nrussell Jul 27 '15 at 18:40
  • Indeed it is. I'd like to see that as an answer and why it works. I've never seen it before. – Benjamin Jul 27 '15 at 18:42
  • [_caveat emptor_](http://stackoverflow.com/questions/16275149/does-ifelse-really-calculate-both-of-its-vectors-every-time-is-it-slow) for all new `R` users considering an `ifelse` solution. – MichaelChirico Jul 27 '15 at 18:42
  • It is just one of the ways like `(year==2001)+0L` or `(year==2001)*1L` to coerce to integer. But, I think it should be faster than the other ways. I had seen @Frank using this kind of code golfing. – akrun Jul 27 '15 at 18:43
  • I have tried only for logical to binary conversion. Do you have any specific example where it should be applied? – akrun Jul 27 '15 at 18:48
  • Not really. I was just trying to understand it. If I can find documentation for this behavior that'd be awesome. I guess it's time to actually read the ?'+' docs – Benjamin Jul 27 '15 at 18:53
  • "Unary + and unary - return a numeric or complex vector. All attributes (including class) are preserved if there is no coercion: logical x is coerced to integer and names, dims and dimnames are preserved." Looks like it will work for anything that has a valid unary `+` method...the primary examples being numerical and logical. – Benjamin Jul 27 '15 at 19:20
4

Just do

 df1$new <- +(df1$year==2001)
akrun
  • 874,273
  • 37
  • 540
  • 662