How to create a new variable in a data.frame based on a condition?

前端 未结 2 1767
梦谈多话
梦谈多话 2020-12-24 14:51

Assume we have a dataframe

x   y
1   1
2   4 
4   5 

how can you add a new variable to the dataframe such that if x is less than or equal

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-24 15:19

    If you have a very limited number of levels, you could try converting y into factor and change its levels.

    > xy <- data.frame(x = c(1, 2, 4), y = c(1, 4, 5))
    > xy$w <- as.factor(xy$y)
    > levels(xy$w) <- c("good", "fair", "bad")
    > xy
      x y    w
    1 1 1 good
    2 2 4 fair
    3 4 5  bad
    

提交回复
热议问题