使用函数和sapply更新数据框

mik*_*sey 0 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
Run Code Online (Sandbox Code Playgroud)

我试图写的功能是这样的:

updateCountry <- function(x) {
  if (clients$Country == "US") {
        clients$CountryType <- "US"
  } else {
    clients$CountryType <- "Foreign"
    }
}
Run Code Online (Sandbox Code Playgroud)

我会像这样应用它:

sapply(clients, updateCountry)
Run Code Online (Sandbox Code Playgroud)

当我遇到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
Run Code Online (Sandbox Code Playgroud)

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

Das*_*son 5

ifelse看起来像你真正想要的.它是if/else构造的矢量化版本.

 clients$CountryType <- ifelse(clients$Country == "US", "US", "Foreign")
Run Code Online (Sandbox Code Playgroud)