使用函数和sapply更新数据框

时间:2012-10-05 15:14:05

标签: r sapply

我试图在数据框中设置一个等于“US”或“Foreign”的列,具体取决于国家/地区。我认为这样做的正确方法是编写一个函数,然后使用sapply来实际更新数据帧。这是我第一次在R中尝试过这样的事情 - 在SQL中,我会写一个UPDATE查询。

这是我的数据框:

str(clients)
'data.frame':   252774 obs. of  4 variables:
 $ ClientID     : Factor w/ 252774 levels "58187855","59210128",..: 19 20 21 22 23 24 25 26 27 28 ...
 $ Country          : Factor w/ 207 levels "Afghanistan",..: 196 60 139 196 196 40 40 196 196 196 ...
 $ CountryType     : chr  "" "" "" "" ...
 $ OrderSize        : num  12.95 21.99 5.00 7.50 44.5 ...


head(clients)
       ClientID  Country       CountryType  OrderSize
1      58187855  United States              12.95
2      59210128  France                     21.99
3      65729284  Pakistan                   5.00
4      25819711  United States              7.50
5      62837458  United States              44.55
6      88379852  China                      99.28

我试图写的功能是:

updateCountry <- function(x) {
  if (clients$Country == "US") {
        clients$CountryType <- "US"
  } else {
    clients$CountryType <- "Foreign"
    }
}

然后我会这样申请:

sapply(clients, updateCountry)

当我对数据框的头部运行sapply时,我得到了这个:

"US" "US" "US" "US" "US" "US" 
Warning messages:
1: In if (clients$Country == "United States") { :
  the condition has length > 1 and only the first element will be used
2: In if (clients$Country == "United States") { :
  the condition has length > 1 and only the first element will be used
3: In if (clients$Country == "United States") { :
  the condition has length > 1 and only the first element will be used
4: In if (clients$Country == "United States") { :
  the condition has length > 1 and only the first element will be used
5: In if (clients$Country == "United States") { :
  the condition has length > 1 and only the first element will be used
6: In if (clients$Country == "United States") { :
  the condition has length > 1 and only the first element will be used

该函数似乎正确地对Country进行了分类,但没有正确更新clients $ CountryType列。我究竟做错了什么?另外 - 这是完成数据框更新的最佳方法吗?

1 个答案:

答案 0 :(得分:5)

ifelse似乎就像你真正想要的一样。它是if / else构造的矢量化版本。

 clients$CountryType <- ifelse(clients$Country == "US", "US", "Foreign")