根据关系分配类别

时间:2013-10-01 13:54:47

标签: r

假设我有一个数据集:

    X   Y
1   0 500
2 125 375
3 250 250
4 375 125
5 500 500
6 750 250
  ....
  ....

可以通过以下方式生成:

df <- data.frame(X = c(0,125,250,375,500,750), Y=c(500,375,250,125,500,250))

我需要根据XY的数字关系指定类别值。例如:

if X=0, then assign label A
if Y>X and Y/X=3 then assign label B
if X=Y then assign label C
if X>Y and X/Y=3 then assign label D

基本上,我根据X和Y的比例分配标签:0,0.25,0.75,1。 所以最终的结果是我希望它:

    X   Y   Category
1   0 500   A
2 125 375   B
3 250 250   C
4 375 125   D
5 500 500   C
6 750 250   D
  ....
  ....

我该如何做到这一点?感谢

3 个答案:

答案 0 :(得分:5)

使用data.table

library(data.table)
df <- data.table(X = c(0,125,250,375,500,750), Y=c(500,375,250,125,500,250))

# if X=0, then assign label A
df[X ==0, Label := "A"]
# if Y>X and Y/X=3 then assign label B
df[Y > X & Y/X == 3, Label := "B"]
# if X=Y then assign label C
df[Y == X, Label := "C"]
# if X>Y and X/Y=3 then assign label D
df[X > Y & X/Y == 3, Label := "D"]

     # X   Y Label
# 1:   0 500     A
# 2: 125 375     B
# 3: 250 250     C
# 4: 375 125     D
# 5: 500 500     C
# 6: 750 250     D

使用@Jilber方法和data.table -

df[, Label := ifelse( X > Y & X/Y == 3, "D", 
     ifelse(Y == X,"C",
         ifelse(Y > X & Y/X == 3, "B", "A"
         )
      )
   )
]

答案 1 :(得分:2)

或使用标准data.frame s

df <- within(df, {
  label <- NA
  label[X == 0]           <- "A"
  label[Y > X & Y/X == 3] <- "B"
  label[Y == X]           <- "C"
  label[X > Y & X/Y == 3] <- "D"
})

应使用所需的列

更新df

答案 2 :(得分:1)

使用ifelse

> transform(df, Category=ifelse(X==0, "A",
                                ifelse(Y>X & Y/X==3, "B", 
                                       ifelse(X==Y, "C", "D"))))
    X   Y Category
1   0 500        A
2 125 375        B
3 250 250        C
4 375 125        D
5 500 500        C
6 750 250        D