0
국가에 따라 데이터 프레임에 'US'또는 'Foreign'과 같은 열을 설정하려고합니다. 적절한 방법은 함수를 작성한 다음 sapply
을 사용하여 실제로 데이터 프레임을 업데이트하는 것입니다. 이것은 R
- SQL
에 이런 식으로 시도한 것은 처음입니다. UPDATE
쿼리를 작성했을 것입니다.함수 및 sapply를 사용하여 데이터 프레임 업데이트
updateCountry <- function(x) {
if (clients$Country == "US") {
clients$CountryType <- "US"
} else {
clients$CountryType <- "Foreign"
}
}
나는 다음과 같이 적용합니다 : :
sapply(clients, updateCountry)
을 내가 실행하면
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
내가 쓰려고 기능이 있습니다 : 여기
내 dataframe입니다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
이 함수는 국가를 올바르게 분류하지만 클라이언트 $ CountryType 열을 올바르게 업데이트하지 않는 것으로 보입니다. 내가 도대체 뭘 잘못하고있는 겁니까? 또한 데이터 프레임 업데이트를 수행하는 가장 좋은 방법입니까?
훨씬 간단한 접근법. 감사합니다. – mikebmassey
가장 간단한 것이 가장 좋습니다 (SO에서의 Occam 's 면도기 - 파시몬 원칙). +1 –