0

Say I have the following data frame:

dx=data.frame(id=letters[1:4], count=1:4)

#   id count
# 1  a     1
# 2  b     2
# 3  c     3
# 4  d     4

And I would like to (grammatically) add a column that will get the count whenever count<3, otherwise 3, so I'll get the following:

#   id count group
# 1  a     1     1
# 2  b     2     2
# 3  c     3     3
# 4  d     4     3

I thought to use

dx$group=if(dx$count<3){dx$count}else{3}

but it doesn't work on arrays. How can I do it?

Shgidi
  • 154
  • 5
  • 16

1 Answers1

2

In this particular case you can just use pmin (as I stated in the comments above):

df$group <- pmin(df$count, 3)

In general your if/else construction does not work on vectors, but you can use the function ifelse. It takes three arguments: First the condition, then the result if the condition is met and finally the result if the condition is not met. For your example you would write the following:

df$group <- ifelse(df$count < 3, df$count, 3) 

Note that in your example the pmin solution is better. Just mentioning the ifelse solution for completeness.

shadow
  • 21,823
  • 4
  • 63
  • 77