在R中的列之间进行评估

时间:2016-03-13 23:55:25

标签: r dataframe

我有一个数据框如下:

head(df)
##   Item  order_online  order_store
## 1  x           1.9      1.6
## 2  y           5.2      1.6
## 3  z           1.9      3.9
## 4  bh          1.4      4.1
## 5  hj          1.4      4.1
## 6  kj          1.3      1.4

我想在order_onlineorder_store之间进行评估,如果order_online的值大于order_store,请将其标记为online,如果{ {1}}大于在名为market的新列中将其标记为order_store

这样的事情:

store

我做了什么:

我尝试像这样对数据框进行子集化:

##   Item  order_online  order_store   market
## 1  x           1.9      1.6         online
## 2  y           5.2      1.6         online
## 3  z           1.9      3.9         store
## 4  bh          1.4      4.1         store
## 5  hj          1.4      4.1         store
## 6  kj          1.3      1.4         store

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

尝试ifelse

df$market <- ifelse(df$order_online > df$order_store,"online","market")

你的问题没有说明如果相同会发生什么,但也可以处理。

由于您似乎在运行此操作时遇到困难,以下是我们提供完全可重现的示例的方法,该示例显示了此代码如何正确地执行您所要求的内容:

#Read in a coy&pasted version of your example data
df <- read.table(text = "   Item  order_online  order_store
    x           1.9      1.6
                     y           5.2      1.6
                     z           1.9      3.9
                     bh          1.4      4.1
                     hj          1.4      4.1
                     kj          1.3      1.4",header = TRUE)

#Prove that it's exactly what you had 
> df
  Item order_online order_store
1    x          1.9         1.6
2    y          5.2         1.6
3    z          1.9         3.9
4   bh          1.4         4.1
5   hj          1.4         4.1
6   kj          1.3         1.4

#Show that `ifelse` alone generates what you want 
> ifelse(df$order_online > df$order_store,"online","market")
[1] "online" "online" "market" "market" "market" "market"

# Show how adding a column directly works
df$market <- ifelse(df$order_online > df$order_store,"online","market")

#Prove that it worked
> df
  Item order_online order_store market
1    x          1.9         1.6 online
2    y          5.2         1.6 online
3    z          1.9         3.9 market
4   bh          1.4         4.1 market
5   hj          1.4         4.1 market
6   kj          1.3         1.4 market

显然,我输入了"market"而不是"store"