Main Content

categorical형 배열로 데이터에 액세스하기

범주를 기준으로 데이터 선택하기

값을 기준으로 데이터를 선택하는 것이 유용한 때가 자주 있습니다. 이러한 방식으로 데이터를 선택할 경우 한 변수의 값들을 기반으로 하여 논리형 벡터를 생성한 후 이 논리형 벡터를 사용하여 다른 변수에 포함된 값의 서브셋을 선택할 수 있습니다. 숫자형 배열에서 특정 범위에 속하는 값을 찾아서 논리형 벡터를 생성한 다음 데이터 선택에 사용할 수 있습니다. 또한, 특정 이산 값을 찾는 방식으로 논리형 벡터를 생성할 수도 있습니다. categorical형 배열을 사용하면 다음 작업을 쉽게 수행할 수 있습니다.

  • 특정 범주에서 요소 선택. categorical형 배열의 경우, 논리 연산자 == 또는 ~=를 사용하여 특정 범주에 속하거나 속하지 않는 데이터를 선택할 수 있습니다. 특정 범주 그룹에 속하는 데이터를 선택하려면 ismember 함수를 사용하십시오.

    순서형 categorical형 배열의 경우, 부등식 >, >=, <, <= 중 하나를 사용하여 특정 범주보다 크거나 작은 범주에 속하는 데이터를 찾을 수 있습니다.

  • 특정 범주에 속하는 데이터 삭제. 논리 연산자를 사용하여 특정 범주에 속하는 데이터를 포함시키거나 제외시킬 수 있습니다.

  • 정의된 범주에 속하지 않는 요소 찾기. categorical형 배열은 정의된 범주에 속하지 않는 요소를 <undefined>로 나타냅니다. 정의된 값을 갖지 않는 관측값은 isundefined 함수를 사용하여 찾을 수 있습니다.

categorical형 배열을 사용하여 데이터에 액세스하는 일반적인 방법

이 예제에서는 categorical형 배열을 사용하여 인덱싱하고 검색하는 방법을 보여줍니다. 테이블 내에 저장된 categorical형 배열을 사용하여 유사한 방법으로 데이터에 액세스할 수 있습니다.

샘플 데이터 불러오기

샘플 patients.mat MAT 파일에서 약 100명의 환자에 대한 데이터를 불러옵니다.

load patients.mat
whos
  Name                            Size            Bytes  Class      Attributes

  Age                           100x1               800  double               
  Diastolic                     100x1               800  double               
  Gender                        100x1             11412  cell                 
  Height                        100x1               800  double               
  LastName                      100x1             11616  cell                 
  Location                      100x1             14208  cell                 
  SelfAssessedHealthStatus      100x1             11540  cell                 
  Smoker                        100x1               100  logical              
  Systolic                      100x1               800  double               
  Weight                        100x1               800  double               

문자형 벡터로 구성된 셀형 배열에서 categorical형 배열 생성하기

셀형 배열 LocationSelfAssessedHealthStatus에는 범주에 해당하는 데이터가 포함되어 있습니다. 각 셀형 배열에는 문자형 벡터가 들어 있으며, 이 문자형 벡터는 각각 3개의 위치와 4개의 건강 상태를 나타내는 고유한 값 집합에서 취한 값을 가집니다. LocationSelfAssessedHealthStatuscategorical형 배열로 변환하려면 categorical 함수를 사용하십시오. 반면에 셀형 배열 LastName에 들어 있는 성의 목록은 범주에 해당하지 않습니다. 따라서 LastNamestring 함수를 사용하여 string형 배열로 변환합니다.

Location = categorical(Location);
SelfAssessedHealthStatus = categorical(SelfAssessedHealthStatus);
LastName = string(LastName);

하나의 범주에 속하는 멤버가 있는지 검색

categorical형 배열에서 논리 연산자 ==~=를 사용하여 특정 범주에 속하거나 속하지 않는 데이터를 찾을 수 있습니다.

위치 Rampart General Hospital에서 관찰한 환자가 있는지 확인합니다.

any(Location == "Rampart General Hospital")
ans = logical
   0

Rampart General Hospital에서 관찰한 환자는 없습니다.

범주의 그룹에 속하는 멤버가 있는지 검색

ismember를 사용하여 특정 범주의 그룹에 속하는 데이터를 찾을 수 있습니다. 예를 들어, Location을 입력 데이터로 사용하여 ismember를 호출합니다. County General Hospital 또는 VA Hospital에서 관찰한 환자를 식별하는 논리형 벡터를 만듭니다.

Location
Location = 100x1 categorical
     County General Hospital 
     VA Hospital 
     St. Mary's Medical Center 
     VA Hospital 
     County General Hospital 
     St. Mary's Medical Center 
     VA Hospital 
     VA Hospital 
     St. Mary's Medical Center 
     County General Hospital 
     County General Hospital 
     St. Mary's Medical Center 
     VA Hospital 
     VA Hospital 
     St. Mary's Medical Center 
     VA Hospital 
     St. Mary's Medical Center 
     VA Hospital 
     County General Hospital 
     County General Hospital 
     VA Hospital 
     VA Hospital 
     VA Hospital 
     County General Hospital 
     County General Hospital 
     VA Hospital 
     VA Hospital 
     County General Hospital 
     County General Hospital 
     County General Hospital 
      ⋮

VA_CountyGenIndex = ...
    ismember(Location,["County General Hospital","VA Hospital"])
VA_CountyGenIndex = 100x1 logical array

   1
   1
   0
   1
   1
   0
   1
   1
   0
   1
      ⋮

VA_CountyGenIndexLocationCounty General Hospital 또는 VA Hospital 범주에 해당하는 각 요소에 대해 논리값 true(1)를 갖는 100×1 논리형 배열입니다. 출력값 VA_CountyGenIndex에는 0이 아닌 요소가 76개 들어 있습니다.

논리형 벡터 VA_CountyGenIndex를 사용하여 County General Hospital 또는 VA Hospital에서 관찰한 환자의 LastName을 선택합니다.

VA_CountyGenPatients = LastName(VA_CountyGenIndex)
VA_CountyGenPatients = 76x1 string
    "Smith"
    "Johnson"
    "Jones"
    "Brown"
    "Miller"
    "Wilson"
    "Taylor"
    "Anderson"
    "Jackson"
    "White"
    "Martin"
    "Garcia"
    "Martinez"
    "Robinson"
    "Clark"
    "Rodriguez"
    "Lewis"
    "Lee"
    "Walker"
    "Hall"
    "Allen"
    "Young"
    "Hernandez"
    "King"
    "Wright"
    "Lopez"
    "Green"
    "Adams"
    "Baker"
    "Mitchell"
      ⋮

특정 범주의 요소를 선택하여 플로팅하기

summary 함수를 사용하여 범주 이름과 각 범주에 속하는 요소의 개수를 포함하는 요약을 출력합니다.

summary(Location)
     County General Hospital       39 
     St. Mary's Medical Center      24 
     VA Hospital                   37 

Location은 3개의 범주를 갖는 100×1 categorical형 배열입니다. County General Hospital이 39개 요소에 있고, St. Mary's Medical Center가 24개 요소, VA Hospital이 37개 요소에 있습니다.

summary 함수를 사용하여 SelfAssessedHealthStatus에 대한 요약을 출력합니다.

summary(SelfAssessedHealthStatus)
     Excellent      34 
     Fair           15 
     Good           40 
     Poor           11 

SelfAssessedHealthStatus는 4개 범주를 갖는 100×1 categorical형 배열입니다.

논리 연산자 ==를 사용하여 자신의 건강 상태를 Good으로 평가한 환자의 연령에 액세스합니다. 그런 다음, 이 데이터의 히스토그램을 플로팅합니다.

figure()
histogram(Age(SelfAssessedHealthStatus == "Good"))
title("Ages of Patients with Good Health Status")

histogram(Age(SelfAssessedHealthStatus == "Good"))은 자신의 건강 상태를 Good으로 보고한 40명의 환자에 대한 연령 데이터를 플로팅합니다.

특정 범주의 데이터 삭제

논리 연산자를 사용하여 특정 범주의 데이터를 포함시키거나 제외할 수 있습니다. VA Hospital에서 관찰한 환자를 작업 공간 변수 AgeLocation에서 모두 삭제합니다.

Age = Age(Location ~= "VA Hospital");
Location = Location(Location ~= "VA Hospital")
Location = 63x1 categorical
     County General Hospital 
     St. Mary's Medical Center 
     County General Hospital 
     St. Mary's Medical Center 
     St. Mary's Medical Center 
     County General Hospital 
     County General Hospital 
     St. Mary's Medical Center 
     St. Mary's Medical Center 
     St. Mary's Medical Center 
     County General Hospital 
     County General Hospital 
     County General Hospital 
     County General Hospital 
     County General Hospital 
     County General Hospital 
     County General Hospital 
     St. Mary's Medical Center 
     St. Mary's Medical Center 
     County General Hospital 
     St. Mary's Medical Center 
     St. Mary's Medical Center 
     St. Mary's Medical Center 
     County General Hospital 
     County General Hospital 
     County General Hospital 
     County General Hospital 
     County General Hospital 
     County General Hospital 
     St. Mary's Medical Center 
      ⋮

이제, Age는 63×1 숫자형 배열이고, Location은 63×1 categorical형 배열입니다.

Location의 범주와 각 범주에 포함된 요소의 개수를 나열합니다.

summary(Location)
     County General Hospital       39 
     St. Mary's Medical Center      24 
     VA Hospital                    0 

VA Hospital에서 관찰한 환자가 Location에서 삭제되었지만, VA Hospital은 여전히 범주로 남아 있습니다.

removecats 함수를 사용하여 Location의 범주에서 VA Hospital을 제거합니다.

Location = removecats(Location,"VA Hospital");

범주 VA Hospital이 제거되었는지 확인합니다.

categories(Location)
ans = 2x1 cell
    {'County General Hospital'  }
    {'St. Mary's Medical Center'}

Location이 2개의 범주를 갖는 63×1 categorical형 배열입니다.

요소 삭제하기

인덱싱을 통해 요소를 삭제할 수 있습니다. 예를 들어, Location(2:end)를 사용하면 Location의 첫 번째 요소를 제거하고 나머지 요소를 선택할 수 있습니다. 그러나 []을 사용하면 더 쉽게 요소를 삭제할 수 있습니다.

Location(1) = [];
summary(Location)
     County General Hospital       38 
     St. Mary's Medical Center      24 

Location이 2개의 범주를 갖는 62×1 categorical형 배열입니다. 첫 번째 요소를 삭제해도 동일한 범주의 다른 요소에는 아무런 영향을 주지 않으며 범주 자체도 삭제되지 않습니다.

정의되지 않은 요소가 있는지 테스트하기

Location에서 범주 County General Hospital을 제거합니다.

Location = removecats(Location,"County General Hospital");

categorical형 배열인 Location의 처음 8개 요소를 표시합니다.

Location(1:8)
ans = 8x1 categorical
     St. Mary's Medical Center 
     <undefined> 
     St. Mary's Medical Center 
     St. Mary's Medical Center 
     <undefined> 
     <undefined> 
     St. Mary's Medical Center 
     St. Mary's Medical Center 

범주 County General Hospital을 제거한 후, 이전에 이 범주에 속해 있던 요소는 더 이상 Location에 대해 정의된 어떠한 범주에도 속하지 않습니다. 어떠한 범주에도 속하지 않는 categorical형 요소는 정의되지 않은 값으로, <undefined>를 값으로 표시합니다.

함수 isundefined를 사용하여 어떠한 범주에도 속하지 않는 categorical형 배열의 요소를 찾습니다.

undefinedIndex = isundefined(Location);

undefinedIndexLocation에서 정의되지 않은 모든 요소에 대해 논리값 true(1)를 가지는 62×1 categorical형 배열입니다.

정의되지 않은 요소 설정하기

summary 함수를 사용하여 Location에서 정의되지 않은 요소의 개수를 출력합니다. 그런 다음 Location의 처음 5개 요소를 표시합니다.

summary(Location)
     St. Mary's Medical Center      24 
     <undefined>                   38 
Location(1:5)
ans = 5x1 categorical
     St. Mary's Medical Center 
     <undefined> 
     St. Mary's Medical Center 
     St. Mary's Medical Center 
     <undefined> 

Location의 첫 번째 요소는 범주 St. Mary's Medical Center에 속합니다. 첫 번째 요소를 정의되지 않은 값으로 설정하여 더 이상 어떤 범주에도 속하지 않도록 만듭니다. 권장되는 방법은 missing 함수를 사용하여 정의되지 않은 값을 만드는 것입니다. 또 다른 방법은 배열의 요소에 '' 또는 ""를 할당하는 것입니다. 이러한 값을 categorical형 배열의 요소에 할당하면 해당 요소는 정의되지 않은 값으로 변환됩니다.

Location(1) = missing;
Location(3) = '';
Location(1:5)
ans = 5x1 categorical
     <undefined> 
     <undefined> 
     <undefined> 
     St. Mary's Medical Center 
     <undefined> 

summary 함수를 사용해 보면 이 할당으로 인해 정의되지 않은 요소의 개수가 늘어난 것을 알 수 있습니다.

summary(Location)
     St. Mary's Medical Center      22 
     <undefined>                   40 

범주를 제거하거나 다른 요소의 범주를 변경하지 않고도 선택한 요소를 undefined로 설정할 수 있습니다. 알 수 없는 값을 가진 요소임을 나타내려면 정의되지 않은 요소로 설정합니다.

정의되지 않은 요소를 사용하여 categorical형 배열 사전할당(Preallocation)

성능을 개선하기 위해, 정의되지 않은 요소를 사용하여 categorical형 배열의 크기를 사전할당할 수 있습니다. 알려진 위치를 갖는 요소만 포함하는 categorical형 배열을 만듭니다.

definedIndex = ~isundefined(Location);
newLocation = Location(definedIndex);
summary(newLocation)
     St. Mary's Medical Center      22 

newLocation의 크기를 확장하여 200×1 categorical형 배열로 만듭니다. 마지막 새 요소를 정의되지 않은 요소로 설정합니다. 나머지 새 요소에도 모두 정의되지 않은 값이 할당됩니다. 22개의 원래 요소는 기존 값을 유지합니다.

newLocation(200) = missing;
summary(newLocation)
     St. Mary's Medical Center       22 
     <undefined>                   178 

newLocation은 추후에 값을 저장할 수 있는 공간을 배열에 가지고 있습니다.

참고 항목

| | | | | |

관련 예제

세부 정보