Main Content

table でのデータの整理と計算

この例では、MATLAB® table に格納されたデータを整理する方法を示します。また、table に含まれる数値データおよび categorical データを使用して計算を実行する方法も示します。

table と timetable は "コンテナー" であるため、それらの操作は通常の数値配列の操作と多少異なります。この例では、表形式のさまざまな添字モードの使用方法、それらのモードの違い、各モードの状況別の利点と欠点を示します。また、データへのアクセスと代入、変換関数と集計関数の適用、table 変数の異なるデータ型への変換、および結果のプロットの方法も示します。

この例で使用しているエイムズ住宅データは、米国アイオワ州エイムズの住宅用不動産データから取得したものです。元のデータは XLS (Excel® ワークブック) スプレッドシートからダウンロードできます。データの説明はテキスト ファイルとして提供されています。(著作権所有者の許可を得て使用しています。このデータの公開または再配布を希望される場合は、著作権所有者にご連絡ください。)

table へのスプレッドシート データのインポート

スプレッドシートを MATLAB にインポートする最適な方法は、関数 readtable を使用することです。タイムスタンプを含むデータの場合は、関数 readtimetable を使用することもあります。エイムズ住宅データには各住宅が販売された月と年が含まれていますが、月と年は別々の列に格納されています。この場合、readtable を使用した方が簡単です。

住宅データを読み取ります。readtable では、データを URL から直接読み取ることができます。スプレッドシートのすべてのテキスト データを出力 table に string 配列として格納します。また、readtable はファイルから列ヘッダーを読み取ると、それらを table の変数名として使用し、有効な MATLAB 識別子に変換します。元の名前を維持するには、名前と値の引数 'VariableNamingRule' を使用します。

housing = readtable("http://jse.amstat.org/v19n3/decock/AmesHousing.xls","TextType","string");
Warning: Column headers from the file were modified to make them valid MATLAB identifiers before creating variable names for the table. The original column headers are saved in the VariableDescriptions property.
Set 'VariableNamingRule' to 'preserve' to use the original column headers as table variable names.

housing を表示します。table には、スプレッドシートの列ごとに 1 つずつ 82 個の変数が含まれます。

housing
housing=2930×82 table
    Order        PID         MSSubClass    MSZoning    LotFrontage    LotArea    Street    Alley    LotShape    LandContour    Utilities    LotConfig    LandSlope    Neighborhood    Condition1    Condition2    BldgType    HouseStyle    OverallQual    OverallCond    YearBuilt    YearRemod_Add    RoofStyle    RoofMatl     Exterior1st    Exterior2nd    MasVnrType    MasVnrArea    ExterQual    ExterCond    Foundation    BsmtQual    BsmtCond    BsmtExposure    BsmtFinType1    BsmtFinSF1    BsmtFinType2    BsmtFinSF2    BsmtUnfSF    TotalBsmtSF    Heating    HeatingQC    CentralAir    Electrical    x1stFlrSF    x2ndFlrSF    LowQualFinSF    GrLivArea    BsmtFullBath    BsmtHalfBath    FullBath    HalfBath    BedroomAbvGr    KitchenAbvGr    KitchenQual    TotRmsAbvGrd    Functional    Fireplaces    FireplaceQu    GarageType    GarageYrBlt    GarageFinish    GarageCars    GarageArea    GarageQual    GarageCond    PavedDrive    WoodDeckSF    OpenPorchSF    EnclosedPorch    x3SsnPorch    ScreenPorch    PoolArea    PoolQC     Fence     MiscFeature    MiscVal    MoSold    YrSold    SaleType    SaleCondition    SalePrice
    _____    ____________    __________    ________    ___________    _______    ______    _____    ________    ___________    _________    _________    _________    ____________    __________    __________    ________    __________    ___________    ___________    _________    _____________    _________    _________    ___________    ___________    __________    __________    _________    _________    __________    ________    ________    ____________    ____________    __________    ____________    __________    _________    ___________    _______    _________    __________    __________    _________    _________    ____________    _________    ____________    ____________    ________    ________    ____________    ____________    ___________    ____________    __________    __________    ___________    __________    ___________    ____________    __________    __________    __________    __________    __________    __________    ___________    _____________    __________    ___________    ________    ______    _______    ___________    _______    ______    ______    ________    _____________    _________

      1      "0526301100"      "020"         "RL"          141         31770     "Pave"    "NA"      "IR1"         "Lvl"       "AllPub"     "Corner"       "Gtl"       "NAmes"         "Norm"         "Norm"      "1Fam"       "1Story"          6              5           1960           1960          "Hip"       "CompShg"     "BrkFace"      "Plywood"     "Stone"          112          "TA"         "TA"        "CBlock"       "TA"        "Gd"          "Gd"           "BLQ"            639          "Unf"              0          441          1080        "GasA"       "Fa"          "Y"         "SBrkr"        1656            0            0            1656            1               0             1           0             3               1             "TA"              7           "Typ"           2            "Gd"        "Attchd"         1960           "Fin"            2            528           "TA"          "TA"          "P"           210             62               0             0               0           0         "NA"     "NA"         "NA"              0       5        2010       "WD"        "Normal"        2.15e+05
      2      "0526350040"      "020"         "RH"           80         11622     "Pave"    "NA"      "Reg"         "Lvl"       "AllPub"     "Inside"       "Gtl"       "NAmes"         "Feedr"        "Norm"      "1Fam"       "1Story"          5              6           1961           1961          "Gable"     "CompShg"     "VinylSd"      "VinylSd"     "None"             0          "TA"         "TA"        "CBlock"       "TA"        "TA"          "No"           "Rec"            468          "LwQ"            144          270           882        "GasA"       "TA"          "Y"         "SBrkr"         896            0            0             896            0               0             1           0             2               1             "TA"              5           "Typ"           0            "NA"        "Attchd"         1961           "Unf"            1            730           "TA"          "TA"          "Y"           140              0               0             0             120           0         "NA"     "MnPrv"      "NA"              0       6        2010       "WD"        "Normal"        1.05e+05
      3      "0526351010"      "020"         "RL"           81         14267     "Pave"    "NA"      "IR1"         "Lvl"       "AllPub"     "Corner"       "Gtl"       "NAmes"         "Norm"         "Norm"      "1Fam"       "1Story"          6              6           1958           1958          "Hip"       "CompShg"     "Wd Sdng"      "Wd Sdng"     "BrkFace"        108          "TA"         "TA"        "CBlock"       "TA"        "TA"          "No"           "ALQ"            923          "Unf"              0          406          1329        "GasA"       "TA"          "Y"         "SBrkr"        1329            0            0            1329            0               0             1           1             3               1             "Gd"              6           "Typ"           0            "NA"        "Attchd"         1958           "Unf"            1            312           "TA"          "TA"          "Y"           393             36               0             0               0           0         "NA"     "NA"         "Gar2"        12500       6        2010       "WD"        "Normal"        1.72e+05
      4      "0526353030"      "020"         "RL"           93         11160     "Pave"    "NA"      "Reg"         "Lvl"       "AllPub"     "Corner"       "Gtl"       "NAmes"         "Norm"         "Norm"      "1Fam"       "1Story"          7              5           1968           1968          "Hip"       "CompShg"     "BrkFace"      "BrkFace"     "None"             0          "Gd"         "TA"        "CBlock"       "TA"        "TA"          "No"           "ALQ"           1065          "Unf"              0         1045          2110        "GasA"       "Ex"          "Y"         "SBrkr"        2110            0            0            2110            1               0             2           1             3               1             "Ex"              8           "Typ"           2            "TA"        "Attchd"         1968           "Fin"            2            522           "TA"          "TA"          "Y"             0              0               0             0               0           0         "NA"     "NA"         "NA"              0       4        2010       "WD"        "Normal"        2.44e+05
      5      "0527105010"      "060"         "RL"           74         13830     "Pave"    "NA"      "IR1"         "Lvl"       "AllPub"     "Inside"       "Gtl"       "Gilbert"       "Norm"         "Norm"      "1Fam"       "2Story"          5              5           1997           1998          "Gable"     "CompShg"     "VinylSd"      "VinylSd"     "None"             0          "TA"         "TA"        "PConc"        "Gd"        "TA"          "No"           "GLQ"            791          "Unf"              0          137           928        "GasA"       "Gd"          "Y"         "SBrkr"         928          701            0            1629            0               0             2           1             3               1             "TA"              6           "Typ"           1            "TA"        "Attchd"         1997           "Fin"            2            482           "TA"          "TA"          "Y"           212             34               0             0               0           0         "NA"     "MnPrv"      "NA"              0       3        2010       "WD"        "Normal"       1.899e+05
      6      "0527105030"      "060"         "RL"           78          9978     "Pave"    "NA"      "IR1"         "Lvl"       "AllPub"     "Inside"       "Gtl"       "Gilbert"       "Norm"         "Norm"      "1Fam"       "2Story"          6              6           1998           1998          "Gable"     "CompShg"     "VinylSd"      "VinylSd"     "BrkFace"         20          "TA"         "TA"        "PConc"        "TA"        "TA"          "No"           "GLQ"            602          "Unf"              0          324           926        "GasA"       "Ex"          "Y"         "SBrkr"         926          678            0            1604            0               0             2           1             3               1             "Gd"              7           "Typ"           1            "Gd"        "Attchd"         1998           "Fin"            2            470           "TA"          "TA"          "Y"           360             36               0             0               0           0         "NA"     "NA"         "NA"              0       6        2010       "WD"        "Normal"       1.955e+05
      7      "0527127150"      "120"         "RL"           41          4920     "Pave"    "NA"      "Reg"         "Lvl"       "AllPub"     "Inside"       "Gtl"       "StoneBr"       "Norm"         "Norm"      "TwnhsE"     "1Story"          8              5           2001           2001          "Gable"     "CompShg"     "CemntBd"      "CmentBd"     "None"             0          "Gd"         "TA"        "PConc"        "Gd"        "TA"          "Mn"           "GLQ"            616          "Unf"              0          722          1338        "GasA"       "Ex"          "Y"         "SBrkr"        1338            0            0            1338            1               0             2           0             2               1             "Gd"              6           "Typ"           0            "NA"        "Attchd"         2001           "Fin"            2            582           "TA"          "TA"          "Y"             0              0             170             0               0           0         "NA"     "NA"         "NA"              0       4        2010       "WD"        "Normal"       2.135e+05
      8      "0527145080"      "120"         "RL"           43          5005     "Pave"    "NA"      "IR1"         "HLS"       "AllPub"     "Inside"       "Gtl"       "StoneBr"       "Norm"         "Norm"      "TwnhsE"     "1Story"          8              5           1992           1992          "Gable"     "CompShg"     "HdBoard"      "HdBoard"     "None"             0          "Gd"         "TA"        "PConc"        "Gd"        "TA"          "No"           "ALQ"            263          "Unf"              0         1017          1280        "GasA"       "Ex"          "Y"         "SBrkr"        1280            0            0            1280            0               0             2           0             2               1             "Gd"              5           "Typ"           0            "NA"        "Attchd"         1992           "RFn"            2            506           "TA"          "TA"          "Y"             0             82               0             0             144           0         "NA"     "NA"         "NA"              0       1        2010       "WD"        "Normal"       1.915e+05
      9      "0527146030"      "120"         "RL"           39          5389     "Pave"    "NA"      "IR1"         "Lvl"       "AllPub"     "Inside"       "Gtl"       "StoneBr"       "Norm"         "Norm"      "TwnhsE"     "1Story"          8              5           1995           1996          "Gable"     "CompShg"     "CemntBd"      "CmentBd"     "None"             0          "Gd"         "TA"        "PConc"        "Gd"        "TA"          "No"           "GLQ"           1180          "Unf"              0          415          1595        "GasA"       "Ex"          "Y"         "SBrkr"        1616            0            0            1616            1               0             2           0             2               1             "Gd"              5           "Typ"           1            "TA"        "Attchd"         1995           "RFn"            2            608           "TA"          "TA"          "Y"           237            152               0             0               0           0         "NA"     "NA"         "NA"              0       3        2010       "WD"        "Normal"       2.365e+05
     10      "0527162130"      "060"         "RL"           60          7500     "Pave"    "NA"      "Reg"         "Lvl"       "AllPub"     "Inside"       "Gtl"       "Gilbert"       "Norm"         "Norm"      "1Fam"       "2Story"          7              5           1999           1999          "Gable"     "CompShg"     "VinylSd"      "VinylSd"     "None"             0          "TA"         "TA"        "PConc"        "TA"        "TA"          "No"           "Unf"              0          "Unf"              0          994           994        "GasA"       "Gd"          "Y"         "SBrkr"        1028          776            0            1804            0               0             2           1             3               1             "Gd"              7           "Typ"           1            "TA"        "Attchd"         1999           "Fin"            2            442           "TA"          "TA"          "Y"           140             60               0             0               0           0         "NA"     "NA"         "NA"              0       6        2010       "WD"        "Normal"        1.89e+05
     11      "0527163010"      "060"         "RL"           75         10000     "Pave"    "NA"      "IR1"         "Lvl"       "AllPub"     "Corner"       "Gtl"       "Gilbert"       "Norm"         "Norm"      "1Fam"       "2Story"          6              5           1993           1994          "Gable"     "CompShg"     "HdBoard"      "HdBoard"     "None"             0          "TA"         "TA"        "PConc"        "Gd"        "TA"          "No"           "Unf"              0          "Unf"              0          763           763        "GasA"       "Gd"          "Y"         "SBrkr"         763          892            0            1655            0               0             2           1             3               1             "TA"              7           "Typ"           1            "TA"        "Attchd"         1993           "Fin"            2            440           "TA"          "TA"          "Y"           157             84               0             0               0           0         "NA"     "NA"         "NA"              0       4        2010       "WD"        "Normal"       1.759e+05
     12      "0527165230"      "020"         "RL"          NaN          7980     "Pave"    "NA"      "IR1"         "Lvl"       "AllPub"     "Inside"       "Gtl"       "Gilbert"       "Norm"         "Norm"      "1Fam"       "1Story"          6              7           1992           2007          "Gable"     "CompShg"     "HdBoard"      "HdBoard"     "None"             0          "TA"         "Gd"        "PConc"        "Gd"        "TA"          "No"           "ALQ"            935          "Unf"              0          233          1168        "GasA"       "Ex"          "Y"         "SBrkr"        1187            0            0            1187            1               0             2           0             3               1             "TA"              6           "Typ"           0            "NA"        "Attchd"         1992           "Fin"            2            420           "TA"          "TA"          "Y"           483             21               0             0               0           0         "NA"     "GdPrv"      "Shed"          500       3        2010       "WD"        "Normal"        1.85e+05
     13      "0527166040"      "060"         "RL"           63          8402     "Pave"    "NA"      "IR1"         "Lvl"       "AllPub"     "Inside"       "Gtl"       "Gilbert"       "Norm"         "Norm"      "1Fam"       "2Story"          6              5           1998           1998          "Gable"     "CompShg"     "VinylSd"      "VinylSd"     "None"             0          "TA"         "TA"        "PConc"        "Gd"        "TA"          "No"           "Unf"              0          "Unf"              0          789           789        "GasA"       "Gd"          "Y"         "SBrkr"         789          676            0            1465            0               0             2           1             3               1             "TA"              7           "Typ"           1            "Gd"        "Attchd"         1998           "Fin"            2            393           "TA"          "TA"          "Y"             0             75               0             0               0           0         "NA"     "NA"         "NA"              0       5        2010       "WD"        "Normal"       1.804e+05
     14      "0527180040"      "020"         "RL"           85         10176     "Pave"    "NA"      "Reg"         "Lvl"       "AllPub"     "Inside"       "Gtl"       "Gilbert"       "Norm"         "Norm"      "1Fam"       "1Story"          7              5           1990           1990          "Gable"     "CompShg"     "HdBoard"      "HdBoard"     "None"             0          "TA"         "TA"        "PConc"        "Gd"        "TA"          "Gd"           "GLQ"            637          "Unf"              0          663          1300        "GasA"       "Gd"          "Y"         "SBrkr"        1341            0            0            1341            1               0             1           1             2               1             "Gd"              5           "Typ"           1            "Po"        "Attchd"         1990           "Unf"            2            506           "TA"          "TA"          "Y"           192              0               0             0               0           0         "NA"     "NA"         "NA"              0       2        2010       "WD"        "Normal"       1.715e+05
     15      "0527182190"      "120"         "RL"          NaN          6820     "Pave"    "NA"      "IR1"         "Lvl"       "AllPub"     "Corner"       "Gtl"       "StoneBr"       "Norm"         "Norm"      "TwnhsE"     "1Story"          8              5           1985           1985          "Gable"     "CompShg"     "HdBoard"      "HdBoard"     "None"             0          "Gd"         "TA"        "PConc"        "Gd"        "TA"          "Av"           "GLQ"            368          "BLQ"           1120            0          1488        "GasA"       "TA"          "Y"         "SBrkr"        1502            0            0            1502            1               0             1           1             1               1             "Gd"              4           "Typ"           0            "NA"        "Attchd"         1985           "RFn"            2            528           "TA"          "TA"          "Y"             0             54               0             0             140           0         "NA"     "NA"         "NA"              0       6        2010       "WD"        "Normal"        2.12e+05
     16      "0527216070"      "060"         "RL"           47         53504     "Pave"    "NA"      "IR2"         "HLS"       "AllPub"     "CulDSac"      "Mod"       "StoneBr"       "Norm"         "Norm"      "1Fam"       "2Story"          8              5           2003           2003          "Hip"       "CompShg"     "CemntBd"      "Wd Shng"     "BrkFace"        603          "Ex"         "TA"        "PConc"        "Gd"        "TA"          "Gd"           "ALQ"           1416          "Unf"              0          234          1650        "GasA"       "Ex"          "Y"         "SBrkr"        1690         1589            0            3279            1               0             3           1             4               1             "Ex"             12           "Mod"           1            "Gd"        "BuiltIn"        2003           "Fin"            3            841           "TA"          "TA"          "Y"           503             36               0             0             210           0         "NA"     "NA"         "NA"              0       6        2010       "WD"        "Normal"        5.38e+05
      ⋮

スプレッドシートには、スペースを含む列ヘッダーや数字で始まる列ヘッダーが含まれています。列ヘッダーは出力 table で変数名になります。既定では、readtable は、スペースを含む名前についてはキャメル ケースを使用して標準化し、数字で始まる名前については先頭に 'x' を付加して標準化します。table の変数名にスペースやその他の英数字以外の文字が含まれていても問題はありませんが、この標準化により、table の変数名をより自然に扱えるようになります。名前を標準化する前に、readtable は元の列ヘッダーを housing.Properties.VariableDescriptions に保存します。

housing.Properties.VariableDescriptions
ans = 1×82 cell
    {'Order'}    {'PID'}    {'MS SubClass'}    {'MS Zoning'}    {'Lot Frontage'}    {'Lot Area'}    {'Street'}    {'Alley'}    {'Lot Shape'}    {'Land Contour'}    {'Utilities'}    {'Lot Config'}    {'Land Slope'}    {'Neighborhood'}    {'Condition 1'}    {'Condition 2'}    {'Bldg Type'}    {'House Style'}    {'Overall Qual'}    {'Overall Cond'}    {'Year Built'}    {'Year Remod/Add'}    {'Roof Style'}    {'Roof Matl'}    {'Exterior 1st'}    {'Exterior 2nd'}    {'Mas Vnr Type'}    {'Mas Vnr Area'}    {'Exter Qual'}    {'Exter Cond'}    {'Foundation'}    {'Bsmt Qual'}    {'Bsmt Cond'}    {'Bsmt Exposure'}    {'BsmtFin Type 1'}    {'BsmtFin SF 1'}    {'BsmtFin Type 2'}    {'BsmtFin SF 2'}    {'Bsmt Unf SF'}    {'Total Bsmt SF'}    {'Heating'}    {'Heating QC'}    {'Central Air'}    {'Electrical'}    {'1st Flr SF'}    {'2nd Flr SF'}    {'Low Qual Fin SF'}    {'Gr Liv Area'}    {'Bsmt Full Bath'}    {'Bsmt Half Bath'}    {'Full Bath'}    {'Half Bath'}    {'Bedroom AbvGr'}    {'Kitchen AbvGr'}    {'Kitchen Qual'}    {'TotRms AbvGrd'}    {'Functional'}    {'Fireplaces'}    {'Fireplace Qu'}    {'Garage Type'}    {'Garage Yr Blt'}    {'Garage Finish'}    {'Garage Cars'}    {'Garage Area'}    {'Garage Qual'}    {'Garage Cond'}    {'Paved Drive'}    {'Wood Deck SF'}    {'Open Porch SF'}    {'Enclosed Porch'}    {'3Ssn Porch'}    {'Screen Porch'}    {'Pool Area'}    {'Pool QC'}    {'Fence'}    {'Misc Feature'}    {'Misc Val'}    {'Mo Sold'}    {'Yr Sold'}    {'Sale Type'}    {'Sale Condition'}    {'SalePrice'}

この例では、元の変数名は必要ありません。それらを削除するには、VariableDescriptions プロパティに空の cell 配列を代入します。

housing.Properties.VariableDescriptions = {};

解析前のデータの整理

変数 Order は行インデックスであり、必要がないため削除できます。table から 1 つの変数を削除するには、行列から行または列を削除する場合と同じように、その変数に空の配列 [] を代入します。

housing.Order = [];

table には 81 個の変数が残っています。住宅価格の完全な解析のためには、ほとんどが重要な変数であるかもしれません。ただし、この例では、はるかに小さいサブセットしか必要ありません。不要な変数を 1 つずつ削除するのは手間がかかります。関数 removevars を使用するとそれらを一度にすべて削除できますが、ここではもっと簡単な方法があります。まず、保持する変数をリストします。次に、添字を使用してそれらを選択し、それ以外を削除します。多くの場合、変数は名前で選択した方が、それらの数値インデックスを特定するよりもはるかに簡単です。

keep = ["PID" "MSSubClass" "LotFrontage", "LotArea" "Neighborhood" "BldgType" ...
        "OverallCond" "YearBuilt" "YearRemod_Add" "Foundation" "Heating" ...
        "CentralAir" "x1stFlrSF" "x2ndFlrSF" "LowQualFinSF" "GrLivArea" ...
        "BsmtFullBath" "BsmtHalfBath" "FullBath" "HalfBath" "BedroomAbvGr" ...
        "GarageType" "MoSold" "YrSold" "SalePrice"];
housing = housing(:,keep)
housing=2930×25 table
        PID         MSSubClass    LotFrontage    LotArea    Neighborhood    BldgType    OverallCond    YearBuilt    YearRemod_Add    Foundation    Heating    CentralAir    x1stFlrSF    x2ndFlrSF    LowQualFinSF    GrLivArea    BsmtFullBath    BsmtHalfBath    FullBath    HalfBath    BedroomAbvGr    GarageType    MoSold    YrSold    SalePrice
    ____________    __________    ___________    _______    ____________    ________    ___________    _________    _____________    __________    _______    __________    _________    _________    ____________    _________    ____________    ____________    ________    ________    ____________    __________    ______    ______    _________

    "0526301100"      "020"           141         31770      "NAmes"        "1Fam"           5           1960           1960          "CBlock"     "GasA"        "Y"          1656            0            0            1656            1               0             1           0             3          "Attchd"        5        2010      2.15e+05
    "0526350040"      "020"            80         11622      "NAmes"        "1Fam"           6           1961           1961          "CBlock"     "GasA"        "Y"           896            0            0             896            0               0             1           0             2          "Attchd"        6        2010      1.05e+05
    "0526351010"      "020"            81         14267      "NAmes"        "1Fam"           6           1958           1958          "CBlock"     "GasA"        "Y"          1329            0            0            1329            0               0             1           1             3          "Attchd"        6        2010      1.72e+05
    "0526353030"      "020"            93         11160      "NAmes"        "1Fam"           5           1968           1968          "CBlock"     "GasA"        "Y"          2110            0            0            2110            1               0             2           1             3          "Attchd"        4        2010      2.44e+05
    "0527105010"      "060"            74         13830      "Gilbert"      "1Fam"           5           1997           1998          "PConc"      "GasA"        "Y"           928          701            0            1629            0               0             2           1             3          "Attchd"        3        2010     1.899e+05
    "0527105030"      "060"            78          9978      "Gilbert"      "1Fam"           6           1998           1998          "PConc"      "GasA"        "Y"           926          678            0            1604            0               0             2           1             3          "Attchd"        6        2010     1.955e+05
    "0527127150"      "120"            41          4920      "StoneBr"      "TwnhsE"         5           2001           2001          "PConc"      "GasA"        "Y"          1338            0            0            1338            1               0             2           0             2          "Attchd"        4        2010     2.135e+05
    "0527145080"      "120"            43          5005      "StoneBr"      "TwnhsE"         5           1992           1992          "PConc"      "GasA"        "Y"          1280            0            0            1280            0               0             2           0             2          "Attchd"        1        2010     1.915e+05
    "0527146030"      "120"            39          5389      "StoneBr"      "TwnhsE"         5           1995           1996          "PConc"      "GasA"        "Y"          1616            0            0            1616            1               0             2           0             2          "Attchd"        3        2010     2.365e+05
    "0527162130"      "060"            60          7500      "Gilbert"      "1Fam"           5           1999           1999          "PConc"      "GasA"        "Y"          1028          776            0            1804            0               0             2           1             3          "Attchd"        6        2010      1.89e+05
    "0527163010"      "060"            75         10000      "Gilbert"      "1Fam"           5           1993           1994          "PConc"      "GasA"        "Y"           763          892            0            1655            0               0             2           1             3          "Attchd"        4        2010     1.759e+05
    "0527165230"      "020"           NaN          7980      "Gilbert"      "1Fam"           7           1992           2007          "PConc"      "GasA"        "Y"          1187            0            0            1187            1               0             2           0             3          "Attchd"        3        2010      1.85e+05
    "0527166040"      "060"            63          8402      "Gilbert"      "1Fam"           5           1998           1998          "PConc"      "GasA"        "Y"           789          676            0            1465            0               0             2           1             3          "Attchd"        5        2010     1.804e+05
    "0527180040"      "020"            85         10176      "Gilbert"      "1Fam"           5           1990           1990          "PConc"      "GasA"        "Y"          1341            0            0            1341            1               0             1           1             2          "Attchd"        2        2010     1.715e+05
    "0527182190"      "120"           NaN          6820      "StoneBr"      "TwnhsE"         5           1985           1985          "PConc"      "GasA"        "Y"          1502            0            0            1502            1               0             1           1             1          "Attchd"        6        2010      2.12e+05
    "0527216070"      "060"            47         53504      "StoneBr"      "1Fam"           5           2003           2003          "PConc"      "GasA"        "Y"          1690         1589            0            3279            1               0             3           1             4          "BuiltIn"       6        2010      5.38e+05
      ⋮

変数名に、わかりにくい名前が 2 つあります。VariableNames プロパティを使用して、それらの変数名をわかりやすい名前に変更します。

housing.Properties.VariableNames(["GrLivArea" "LowQualFinSF"]) = ["TotalAboveGroundLivingArea" "LowQualFinishedArea"];

さらに、'x' で始まる変数名で、正しくないように見えるものが 2 つあります。それらの名前を変更するもう 1 つの方法は、関数 renamevars を使用することです。renamevars を使用する場合は、出力を元の table に代入します。そうしないと、更新が失われます。

housing = renamevars(housing,["x1stFlrSF" "x2ndFlrSF"],["FirstFlrArea" "SecondFlrArea"]);

データ型の変換と整理

変数のうちの 6 つは string 配列です。概念的には、それらのすべてに "categorical" データが格納されています。これは、少数の取り得る値またはカテゴリの固定のセットから取得される離散的な数値以外の値です。ほぼすべての場合において、そのようなデータは categorical 配列に変換することが推奨されます。関数 detectImportOptions を使用すると、readtable で読み取るデータのデータ型を制御できます。ただし、最初からやり直さなくても、それらの table 変数を categorical データ型になるように変換できます。たとえば、変数 Neighborhoodcategorical 配列に変換します。

housing.Neighborhood = categorical(housing.Neighborhood);

この代入では、table 内の既存のテキスト変数 Neighborhood が新しい categorical 変数で上書き、すなわち "置換" されます。置換では、代入によってデータ型を変更できます。一方、次の代入ではインデックスを使用しています。

housing.Neighborhood(:) = categorical(housing.Neighborhood)

これは、変数を置換する代わりに、既存のテキスト変数 "自体" に要素単位で値を代入します。この場合、housing.Neighborhood は string 配列のままになります。この動作は、通常のワークスペース変数の動作と一致しています。配列のインデックス付けによる代入では、配列の型は変わりません。たとえば、整数の配列にインデックスを付け、要素に浮動小数点値を代入すると、値は整数部までで切り捨てられて整数として格納されます。

x = uint32([1 2 3]);
x(2) = 2.2 % converted to 2, as a uint32
x = 1×3 uint32 row vector

   1   2   3

ドット表記による代入は、table 内の変数の型を変換する方法の 1 つです。関数 convertvars はもう 1 つの方法であり、この方法には 2 つの利点があります。まず、変数への代入とは異なり、上書きに関する混乱がありません。関数 convertvars は、常に既存の変数を上書きし、それらの型を変換します。2 番目に、convertvars では複数の変数を一度に処理できます。housing には、categorical データ型への変換が必要なテキスト変数がさらにいくつかあります。それらを一度に 1 つずつ変更すると手間がかかりますが、convertvars では複数の変数を 1 つのコマンドで変換できます。

housing = convertvars(housing,["BldgType" "Foundation"],"categorical");

table 内の変数を名前や位置で明示的にリストする必要はありません。string 配列であるすべての table 変数を検索し、それらを categorical 変数に変換できます。string 配列である table 変数を指定するには、convertvars を呼び出すときに関数ハンドル @isstring を使用します。

housing = convertvars(housing,@isstring,"categorical");

いずれの場合も、convertvars の出力を元の table に再代入します。そうしないと、更新が失われます。

状況によっては、すべてのテキスト変数を categorical に変換するのは適切でない場合もあります。たとえば、現在の住宅所有者の名前がデータに含まれていた場合、それらを categorical 変数に格納しても意味がありません。住宅所有者の名前は住宅のカテゴリを定義するものではありません。それらの名前については、代わりに string 配列で残しておきます。

もう 1 つの例として、変数 CentralAircategorical に変換された変数の 1 つです。しかし、そのカテゴリは YN だけであるため、logical 変数と見なした方が合理的な可能性があります。

summary(housing.CentralAir)
     N       196 
     Y      2734 

logical データ型 (すべての整数型も同様) では、categorical とは異なり、欠損値 (NaN に相当) が許容されません。ここでは、変数 CentralAir に欠損データ値はありません。CentralAir のデータ型として、logical または categorical のいずれかを使用できます。

any(ismissing(housing.CentralAir))
ans = logical
   0

Ytrue として logical にデータ型を変換し、ドット表記を使用して既存の categorical 変数を新しい logical 変数で上書きします。

housing.CentralAir = (housing.CentralAir == "Y");

housing の変換後のデータを表示します。

housing
housing=2930×25 table
       PID        MSSubClass    LotFrontage    LotArea    Neighborhood    BldgType    OverallCond    YearBuilt    YearRemod_Add    Foundation    Heating    CentralAir    FirstFlrArea    SecondFlrArea    LowQualFinishedArea    TotalAboveGroundLivingArea    BsmtFullBath    BsmtHalfBath    FullBath    HalfBath    BedroomAbvGr    GarageType    MoSold    YrSold    SalePrice
    __________    __________    ___________    _______    ____________    ________    ___________    _________    _____________    __________    _______    __________    ____________    _____________    ___________________    __________________________    ____________    ____________    ________    ________    ____________    __________    ______    ______    _________

    0526301100       020            141         31770       NAmes          1Fam            5           1960           1960           CBlock       GasA        true            1656               0                  0                        1656                    1               0             1           0             3           Attchd         5        2010      2.15e+05
    0526350040       020             80         11622       NAmes          1Fam            6           1961           1961           CBlock       GasA        true             896               0                  0                         896                    0               0             1           0             2           Attchd         6        2010      1.05e+05
    0526351010       020             81         14267       NAmes          1Fam            6           1958           1958           CBlock       GasA        true            1329               0                  0                        1329                    0               0             1           1             3           Attchd         6        2010      1.72e+05
    0526353030       020             93         11160       NAmes          1Fam            5           1968           1968           CBlock       GasA        true            2110               0                  0                        2110                    1               0             2           1             3           Attchd         4        2010      2.44e+05
    0527105010       060             74         13830       Gilbert        1Fam            5           1997           1998           PConc        GasA        true             928             701                  0                        1629                    0               0             2           1             3           Attchd         3        2010     1.899e+05
    0527105030       060             78          9978       Gilbert        1Fam            6           1998           1998           PConc        GasA        true             926             678                  0                        1604                    0               0             2           1             3           Attchd         6        2010     1.955e+05
    0527127150       120             41          4920       StoneBr        TwnhsE          5           2001           2001           PConc        GasA        true            1338               0                  0                        1338                    1               0             2           0             2           Attchd         4        2010     2.135e+05
    0527145080       120             43          5005       StoneBr        TwnhsE          5           1992           1992           PConc        GasA        true            1280               0                  0                        1280                    0               0             2           0             2           Attchd         1        2010     1.915e+05
    0527146030       120             39          5389       StoneBr        TwnhsE          5           1995           1996           PConc        GasA        true            1616               0                  0                        1616                    1               0             2           0             2           Attchd         3        2010     2.365e+05
    0527162130       060             60          7500       Gilbert        1Fam            5           1999           1999           PConc        GasA        true            1028             776                  0                        1804                    0               0             2           1             3           Attchd         6        2010      1.89e+05
    0527163010       060             75         10000       Gilbert        1Fam            5           1993           1994           PConc        GasA        true             763             892                  0                        1655                    0               0             2           1             3           Attchd         4        2010     1.759e+05
    0527165230       020            NaN          7980       Gilbert        1Fam            7           1992           2007           PConc        GasA        true            1187               0                  0                        1187                    1               0             2           0             3           Attchd         3        2010      1.85e+05
    0527166040       060             63          8402       Gilbert        1Fam            5           1998           1998           PConc        GasA        true             789             676                  0                        1465                    0               0             2           1             3           Attchd         5        2010     1.804e+05
    0527180040       020             85         10176       Gilbert        1Fam            5           1990           1990           PConc        GasA        true            1341               0                  0                        1341                    1               0             1           1             2           Attchd         2        2010     1.715e+05
    0527182190       120            NaN          6820       StoneBr        TwnhsE          5           1985           1985           PConc        GasA        true            1502               0                  0                        1502                    1               0             1           1             1           Attchd         6        2010      2.12e+05
    0527216070       060             47         53504       StoneBr        1Fam            5           2003           2003           PConc        GasA        true            1690            1589                  0                        3279                    1               0             3           1             4           BuiltIn        6        2010      5.38e+05
      ⋮

すべてのテキスト データが categorical 変数に変換されています。ただし、整理すべき内容がまだいくつか残っています。

変数 OverallCond は数値配列として読み取られていますが、その値はすべて 110 の整数から取得されます。それらの値を数値データとして残すこともできますが、"順序" categorical データと考えることもできます。categorical 配列が順序配列の場合、そのカテゴリは指定の順序をもちます。たとえば、カテゴリ 105 について 10 > 5 という比較はできますが (状態の評価が 10 である住宅の方が評価が 5 である住宅よりも理論上は良好であるため)、それらの比較において 10 - 5 に数値的な意味はありません。OverallCond が意図せずに数値データとして扱われないように、順序 categorical 配列に変換します。これにより、関係比較は引き続き可能ですが、算術演算は実行されなくなります。12 などのカテゴリ名は解釈しやすく、そのままでかまいません。

housing.OverallCond = categorical(housing.OverallCond,1:10,"Ordinal",true);

同様に、変数 MSSubClass は元のスプレッドシートでは数値コードで構成されていました。それらの値は categorical データであると見なすことができます。それらの特定のコードに数学的な順序はないため、カテゴリは非順序 (または "ノミナル") です。ここでは、コードの先頭のゼロを保持するために、readtable はそれらの値をテキストとして読み取っています。その後に、MSSubClasscategorical データに変換されました。

MSSubClass は必要なデータ型になっていますが、住宅のカテゴリとしては解釈が難しいかもしれません。エイムズ住宅データの説明のファイルに、数値コードの定義が記載されています。それらのカテゴリにわかりやすい名前を付けると、データを理解するのに役立ちます。どの名前がどの数値に対応するかを明確にするために、関数 categorical の別の呼び出しでカテゴリ (code) とその名前 (subclass) の両方を指定します。

code = ["020" "030" "040" "045" "050" "060" "070" "075" "080" "085" "090" "120" "150" "160" "180" "190"];
subclass = ["1-STORY 1946 & NEWER ALL STYLES" ...
            "1-STORY 1945 & OLDER" ...
            "1-STORY W/FINISHED ATTIC ALL AGES" ...
            "1-1/2 STORY - UNFINISHED ALL AGES" ...
            "1-1/2 STORY FINISHED ALL AGES" ...
            "2-STORY 1946 & NEWER" ...
            "2-STORY 1945 & OLDER" ...
            "2-1/2 STORY ALL AGES" ...
            "SPLIT OR MULTI-LEVEL" ...
            "SPLIT FOYER" ...
            "DUPLEX - ALL STYLES AND AGES" ...
            "1-STORY PUD (Planned Unit Development) - 1946 & NEWER" ...
            "1-1/2 STORY PUD - ALL AGES" ...
            "2-STORY PUD - 1946 & NEWER" ...
            "PUD - MULTILEVEL - INCL SPLIT LEV/FOYER" ...
            "2 FAMILY CONVERSION - ALL STYLES AND AGES"];
housing.MSSubClass = categorical(housing.MSSubClass,code,subclass);

変数 BldgType のカテゴリ名は明確でありません。MSSubClass と同様に、より記述的な名前を使用すると建物のカテゴリを理解するのに役立ちます。建物のカテゴリごとの住宅数を表示するには、関数 summary を使用します。

summary(housing.BldgType)
     1Fam        2425 
     2fmCon        62 
     Duplex       109 
     Twnhs        101 
     TwnhsE       233 

5 つのカテゴリだけで、古い名前を指定しなくても、新しいカテゴリ名を正しい順序で問題なくリストできます。カテゴリの名前を変更するには、関数 renamecats を使用します。

types = ["Single-family Detached" "Two-family Conversion" "Duplex" "Townhouse End Unit" "Townhouse Inside Unit"];
housing.BldgType = renamecats(housing.BldgType,types);

変数 GarageType には、Not Applicable (該当なし) を表す NA というカテゴリが含まれています。GarageType では、NA は住宅に駐車場がないことを意味します。しかし、NA は欠損値と混同しがちです。本来の欠損値は、住宅に駐車場があるかどうかがわからないことを意味します。ただし、この住宅データでは、住宅に駐車場があるかどうかがすべてわかっています。意味が明確になるように、その 1 つのカテゴリ名を変更します。

housing.GarageType = renamecats(housing.GarageType,"NA","None");

最後に、変数 PID は string 配列として読み取られています。その値は数値でしたが、一部の値の先頭にゼロが含まれていました。関数 readtable は、この情報を保持するために値を string として格納しています。その後、convertvars の呼び出しで、変数 PIDcategorical 配列に変換されました。PID には、一意の識別番号が格納されています。識別番号は必要に応じて割り当てられるものであり、値の固定のセットから取得されるわけではありません。それらを categorical 変数に格納しても、特に利点はありません。すべての識別番号がカテゴリであるとすると、新しい識別番号が追加されるたびに新しいカテゴリが PID に追加されることになります。PID は string 配列に変換し直した方が便利な可能性があります。値を string に変換するには、関数 string を使用します。

housing.PID = string(housing.PID);

事前にデータを整理した結果を表示します。

housing
housing=2930×25 table
        PID                              MSSubClass                          LotFrontage    LotArea    Neighborhood           BldgType           OverallCond    YearBuilt    YearRemod_Add    Foundation    Heating    CentralAir    FirstFlrArea    SecondFlrArea    LowQualFinishedArea    TotalAboveGroundLivingArea    BsmtFullBath    BsmtHalfBath    FullBath    HalfBath    BedroomAbvGr    GarageType    MoSold    YrSold    SalePrice
    ____________    _____________________________________________________    ___________    _______    ____________    ______________________    ___________    _________    _____________    __________    _______    __________    ____________    _____________    ___________________    __________________________    ____________    ____________    ________    ________    ____________    __________    ______    ______    _________

    "0526301100"    1-STORY 1946 & NEWER ALL STYLES                              141         31770       NAmes         Single-family Detached         5           1960           1960           CBlock       GasA        true            1656               0                  0                        1656                    1               0             1           0             3           Attchd         5        2010      2.15e+05
    "0526350040"    1-STORY 1946 & NEWER ALL STYLES                               80         11622       NAmes         Single-family Detached         6           1961           1961           CBlock       GasA        true             896               0                  0                         896                    0               0             1           0             2           Attchd         6        2010      1.05e+05
    "0526351010"    1-STORY 1946 & NEWER ALL STYLES                               81         14267       NAmes         Single-family Detached         6           1958           1958           CBlock       GasA        true            1329               0                  0                        1329                    0               0             1           1             3           Attchd         6        2010      1.72e+05
    "0526353030"    1-STORY 1946 & NEWER ALL STYLES                               93         11160       NAmes         Single-family Detached         5           1968           1968           CBlock       GasA        true            2110               0                  0                        2110                    1               0             2           1             3           Attchd         4        2010      2.44e+05
    "0527105010"    2-STORY 1946 & NEWER                                          74         13830       Gilbert       Single-family Detached         5           1997           1998           PConc        GasA        true             928             701                  0                        1629                    0               0             2           1             3           Attchd         3        2010     1.899e+05
    "0527105030"    2-STORY 1946 & NEWER                                          78          9978       Gilbert       Single-family Detached         6           1998           1998           PConc        GasA        true             926             678                  0                        1604                    0               0             2           1             3           Attchd         6        2010     1.955e+05
    "0527127150"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER         41          4920       StoneBr       Townhouse Inside Unit          5           2001           2001           PConc        GasA        true            1338               0                  0                        1338                    1               0             2           0             2           Attchd         4        2010     2.135e+05
    "0527145080"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER         43          5005       StoneBr       Townhouse Inside Unit          5           1992           1992           PConc        GasA        true            1280               0                  0                        1280                    0               0             2           0             2           Attchd         1        2010     1.915e+05
    "0527146030"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER         39          5389       StoneBr       Townhouse Inside Unit          5           1995           1996           PConc        GasA        true            1616               0                  0                        1616                    1               0             2           0             2           Attchd         3        2010     2.365e+05
    "0527162130"    2-STORY 1946 & NEWER                                          60          7500       Gilbert       Single-family Detached         5           1999           1999           PConc        GasA        true            1028             776                  0                        1804                    0               0             2           1             3           Attchd         6        2010      1.89e+05
    "0527163010"    2-STORY 1946 & NEWER                                          75         10000       Gilbert       Single-family Detached         5           1993           1994           PConc        GasA        true             763             892                  0                        1655                    0               0             2           1             3           Attchd         4        2010     1.759e+05
    "0527165230"    1-STORY 1946 & NEWER ALL STYLES                              NaN          7980       Gilbert       Single-family Detached         7           1992           2007           PConc        GasA        true            1187               0                  0                        1187                    1               0             2           0             3           Attchd         3        2010      1.85e+05
    "0527166040"    2-STORY 1946 & NEWER                                          63          8402       Gilbert       Single-family Detached         5           1998           1998           PConc        GasA        true             789             676                  0                        1465                    0               0             2           1             3           Attchd         5        2010     1.804e+05
    "0527180040"    1-STORY 1946 & NEWER ALL STYLES                               85         10176       Gilbert       Single-family Detached         5           1990           1990           PConc        GasA        true            1341               0                  0                        1341                    1               0             1           1             2           Attchd         2        2010     1.715e+05
    "0527182190"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER        NaN          6820       StoneBr       Townhouse Inside Unit          5           1985           1985           PConc        GasA        true            1502               0                  0                        1502                    1               0             1           1             1           Attchd         6        2010      2.12e+05
    "0527216070"    2-STORY 1946 & NEWER                                          47         53504       StoneBr       Single-family Detached         5           2003           2003           PConc        GasA        true            1690            1589                  0                        3279                    1               0             3           1             4           BuiltIn        6        2010      5.38e+05
      ⋮

販売日を示す変数の作成

table には、販売日の月と年を示す別々の変数があります。それらの変数を 1 つの datetime 変数に結合すると便利です。新しい変数を table の右端に追加するには、ドット表記を使用した代入が便利です。販売日を新しい変数として追加します。

housing.LastSoldDate = datetime(housing.YrSold,housing.MoSold,0,"Format","MMM yyyy");

次に、元の 2 つの変数を削除します。変数を名前でリストして removevars を使用すると簡単です。

housing = removevars(housing,["YrSold" "MoSold"])
housing=2930×24 table
        PID                              MSSubClass                          LotFrontage    LotArea    Neighborhood           BldgType           OverallCond    YearBuilt    YearRemod_Add    Foundation    Heating    CentralAir    FirstFlrArea    SecondFlrArea    LowQualFinishedArea    TotalAboveGroundLivingArea    BsmtFullBath    BsmtHalfBath    FullBath    HalfBath    BedroomAbvGr    GarageType    SalePrice    LastSoldDate
    ____________    _____________________________________________________    ___________    _______    ____________    ______________________    ___________    _________    _____________    __________    _______    __________    ____________    _____________    ___________________    __________________________    ____________    ____________    ________    ________    ____________    __________    _________    ____________

    "0526301100"    1-STORY 1946 & NEWER ALL STYLES                              141         31770       NAmes         Single-family Detached         5           1960           1960           CBlock       GasA        true            1656               0                  0                        1656                    1               0             1           0             3           Attchd        2.15e+05      Apr 2010  
    "0526350040"    1-STORY 1946 & NEWER ALL STYLES                               80         11622       NAmes         Single-family Detached         6           1961           1961           CBlock       GasA        true             896               0                  0                         896                    0               0             1           0             2           Attchd        1.05e+05      May 2010  
    "0526351010"    1-STORY 1946 & NEWER ALL STYLES                               81         14267       NAmes         Single-family Detached         6           1958           1958           CBlock       GasA        true            1329               0                  0                        1329                    0               0             1           1             3           Attchd        1.72e+05      May 2010  
    "0526353030"    1-STORY 1946 & NEWER ALL STYLES                               93         11160       NAmes         Single-family Detached         5           1968           1968           CBlock       GasA        true            2110               0                  0                        2110                    1               0             2           1             3           Attchd        2.44e+05      Mar 2010  
    "0527105010"    2-STORY 1946 & NEWER                                          74         13830       Gilbert       Single-family Detached         5           1997           1998           PConc        GasA        true             928             701                  0                        1629                    0               0             2           1             3           Attchd       1.899e+05      Feb 2010  
    "0527105030"    2-STORY 1946 & NEWER                                          78          9978       Gilbert       Single-family Detached         6           1998           1998           PConc        GasA        true             926             678                  0                        1604                    0               0             2           1             3           Attchd       1.955e+05      May 2010  
    "0527127150"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER         41          4920       StoneBr       Townhouse Inside Unit          5           2001           2001           PConc        GasA        true            1338               0                  0                        1338                    1               0             2           0             2           Attchd       2.135e+05      Mar 2010  
    "0527145080"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER         43          5005       StoneBr       Townhouse Inside Unit          5           1992           1992           PConc        GasA        true            1280               0                  0                        1280                    0               0             2           0             2           Attchd       1.915e+05      Dec 2009  
    "0527146030"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER         39          5389       StoneBr       Townhouse Inside Unit          5           1995           1996           PConc        GasA        true            1616               0                  0                        1616                    1               0             2           0             2           Attchd       2.365e+05      Feb 2010  
    "0527162130"    2-STORY 1946 & NEWER                                          60          7500       Gilbert       Single-family Detached         5           1999           1999           PConc        GasA        true            1028             776                  0                        1804                    0               0             2           1             3           Attchd        1.89e+05      May 2010  
    "0527163010"    2-STORY 1946 & NEWER                                          75         10000       Gilbert       Single-family Detached         5           1993           1994           PConc        GasA        true             763             892                  0                        1655                    0               0             2           1             3           Attchd       1.759e+05      Mar 2010  
    "0527165230"    1-STORY 1946 & NEWER ALL STYLES                              NaN          7980       Gilbert       Single-family Detached         7           1992           2007           PConc        GasA        true            1187               0                  0                        1187                    1               0             2           0             3           Attchd        1.85e+05      Feb 2010  
    "0527166040"    2-STORY 1946 & NEWER                                          63          8402       Gilbert       Single-family Detached         5           1998           1998           PConc        GasA        true             789             676                  0                        1465                    0               0             2           1             3           Attchd       1.804e+05      Apr 2010  
    "0527180040"    1-STORY 1946 & NEWER ALL STYLES                               85         10176       Gilbert       Single-family Detached         5           1990           1990           PConc        GasA        true            1341               0                  0                        1341                    1               0             1           1             2           Attchd       1.715e+05      Jan 2010  
    "0527182190"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER        NaN          6820       StoneBr       Townhouse Inside Unit          5           1985           1985           PConc        GasA        true            1502               0                  0                        1502                    1               0             1           1             1           Attchd        2.12e+05      May 2010  
    "0527216070"    2-STORY 1946 & NEWER                                          47         53504       StoneBr       Single-family Detached         5           2003           2003           PConc        GasA        true            1690            1589                  0                        3279                    1               0             3           1             4           BuiltIn       5.38e+05      May 2010  
      ⋮

プロットによるデータの確認

簡単なプロットをいくつか作成してデータを確認します。多くの基本的なプロット コマンドでは、table は入力引数として受け入れられません。ただし、ドット表記を使用して 1 つ以上の table 変数をプロット関数に渡すことができます。table から配列を取得し、それらをプロット関数に入力引数として渡します。

たとえば、table から住宅の販売価格の散布図を建てられた年の関数として作成します。

scatter(housing.YearBuilt,housing.SalePrice,20,"filled");

Figure contains an axes object. The axes object contains an object of type scatter.

価格の対数変換を使用すると、年と価格の関係をより簡潔に示せる可能性があります。また、住宅の居住面積を使用してマーカーを色分けすると、より多くの情報を散布図に示すことができます。居住面積は右裾が長いため、面積の対数変換を表示しても効果的です。2 つの table 変数を変換するには、それらを関数 log の呼び出しでラップします。その後、別の散布図を作成します。

logSalePrice = log(housing.SalePrice);
logLivingArea = log(housing.TotalAboveGroundLivingArea);
scatter(housing.YearBuilt,logSalePrice,20,logLivingArea,"filled");

Figure contains an axes object. The axes object contains an object of type scatter.

データの誤りの除去

長い期間にわたって収集された大規模で複雑なデータ セットには、多少の誤りが含まれていることがあります。住宅データに誤りがないかチェックします。データに含まれる日付から始めることをお勧めします。まず、YearBuiltYearRemod_Add と比較します。

checkRows = housing.YearBuilt > housing.YearRemod_Add;
housing(checkRows,:)
ans=1×24 table
        PID                   MSSubClass               LotFrontage    LotArea    Neighborhood           BldgType           OverallCond    YearBuilt    YearRemod_Add    Foundation    Heating    CentralAir    FirstFlrArea    SecondFlrArea    LowQualFinishedArea    TotalAboveGroundLivingArea    BsmtFullBath    BsmtHalfBath    FullBath    HalfBath    BedroomAbvGr    GarageType    SalePrice    LastSoldDate
    ____________    _______________________________    ___________    _______    ____________    ______________________    ___________    _________    _____________    __________    _______    __________    ____________    _____________    ___________________    __________________________    ____________    ____________    ________    ________    ____________    __________    _________    ____________

    "0907194160"    1-STORY 1946 & NEWER ALL STYLES        65          10739       CollgCr       Single-family Detached         5           2002           2001           PConc        GasA        true            1444              0                   0                        1444                    1               0             2           0             3            Attchd      2.03e+05       Mar 2009  

住宅自体が 2002 年に建てられたとすると、2001 年に改築が行われている可能性はありません。YearBuilt の値が誤りであることが判明したと仮定すると (仮定について確認が必要です)、ドット表記を使用して、この住宅が建てられた年に 2001 を代入できます。

housing.YearBuilt(checkRows) = 2001;

もう 1 つのチェックとして、新しい変数 LastSoldDateYearBuilt と比較します。

checkRows = housing.YearBuilt > year(housing.LastSoldDate);
housing(checkRows,:)
ans=2×24 table
        PID                   MSSubClass               LotFrontage    LotArea    Neighborhood           BldgType           OverallCond    YearBuilt    YearRemod_Add    Foundation    Heating    CentralAir    FirstFlrArea    SecondFlrArea    LowQualFinishedArea    TotalAboveGroundLivingArea    BsmtFullBath    BsmtHalfBath    FullBath    HalfBath    BedroomAbvGr    GarageType    SalePrice     LastSoldDate
    ____________    _______________________________    ___________    _______    ____________    ______________________    ___________    _________    _____________    __________    _______    __________    ____________    _____________    ___________________    __________________________    ____________    ____________    ________    ________    ____________    __________    __________    ____________

    "0908154235"    2-STORY 1946 & NEWER                   313         63887       Edwards       Single-family Detached         5           2008           2008           PConc        GasA        true            4692             950                  0                        5642                    2               0             2           1             3            Attchd         1.6e+05      Dec 2007  
    "0908154195"    1-STORY 1946 & NEWER ALL STYLES        128         39290       Edwards       Single-family Detached         5           2008           2009           PConc        GasA        true            5095               0                  0                        5095                    1               1             2           1             2            Attchd      1.8385e+05      Sep 2007  

問題がもう 1 つ見つかります。これらの 2 つの住宅は、変数 LastSoldDate で示されているように 2007 年の後半に販売されています。しかし、YearBuilt の対応する値は 2008 になっています。これらの住宅について、YearBuilt の年が記録されたのが 2008 年の前半であったと考えられます (この仮定についても確認が必要です)。ここでは、ドット表記を使用して 2 つの行に代入することで変数 YearBuilt を更新します。

housing.YearBuilt(checkRows) = 2007;

欠損データの整理

データを整理する次のステップは、数値変数および categorical 変数の欠損データを確認することです。housing には、欠損値をサポートしない logical 変数が 1 つ含まれています。関数 ismissing は、table のどの要素に欠損値があるかを示します。

missingElements = ismissing(housing)
missingElements = 2930×24 logical array

   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
      ⋮

関数 ismissing は、table と同じサイズの logical 行列を返します。その行列の列の合計から、table の各変数にある欠損値の数がわかります。

numMissing = sum(missingElements,1)
numMissing = 1×24

     0     0   490     0     0     0     0     0     0     0     0     0     0     0     0     0     2     2     0     0     0     0     0     0

欠損データがある変数は 3 つだけですが、変数名がないため、どの変数であるかが簡単にはわかりません。これを確認する 1 つの方法として、table の VariableNames プロパティにインデックスを付け、欠損値がある変数に対応する名前を検索することができます。

housing.Properties.VariableNames(numMissing > 0)
ans = 1×3 cell
    {'LotFrontage'}    {'BsmtFullBath'}    {'BsmtHalfBath'}

欠損データに関する処理を決めるのは簡単ではありません。データの欠損がランダムで、欠損値が少しだけであれば、それらの行を table から削除することが 1 つの方法として考えられます。地下のバスルームに関する 4 つの欠損値 (この場合は NaN) は 2 つの行にのみ見られます。それらの 2 つの行を関数 rmmissing を使用して削除できます。

missingBsmtBath = ismissing(housing.BsmtFullBath) | ismissing(housing.BsmtHalfBath);
housing(missingBsmtBath,:)
ans=2×24 table
        PID                   MSSubClass               LotFrontage    LotArea    Neighborhood           BldgType           OverallCond    YearBuilt    YearRemod_Add    Foundation    Heating    CentralAir    FirstFlrArea    SecondFlrArea    LowQualFinishedArea    TotalAboveGroundLivingArea    BsmtFullBath    BsmtHalfBath    FullBath    HalfBath    BedroomAbvGr    GarageType    SalePrice    LastSoldDate
    ____________    _______________________________    ___________    _______    ____________    ______________________    ___________    _________    _____________    __________    _______    __________    ____________    _____________    ___________________    __________________________    ____________    ____________    ________    ________    ____________    __________    _________    ____________

    "0903230120"    1-STORY 1946 & NEWER ALL STYLES         99          5940       BrkSide       Single-family Detached         7           1946           1950           PConc        GasA        true             896              0                   0                         896                   NaN             NaN            1           0             2            Detchd          79000      Mar 2008  
    "0908154080"    1-STORY 1946 & NEWER ALL STYLES        123         47007       Edwards       Single-family Detached         7           1959           1996           Slab         GasA        true            3820              0                   0                        3820                   NaN             NaN            3           1             5            Attchd      2.847e+05      Jun 2008  

housing = rmmissing(housing,"DataVariables",["BsmtFullBath" "BsmtHalfBath"]);
whos housing
  Name            Size             Bytes  Class    Attributes

  housing      2928x24            595935  table              

この rmmissing の呼び出しでは、BsmtFullBathBsmtHalfBath の欠損値がある行のみが削除されます。table には、LotFrontage の値が欠損している行がまだ 490 行残っています。それらの 490 行を削除することも考えられますが、それを行うと 16% を超えるデータが削除されることになります。また、それらの欠損値を関数 fillmissing を使用して間口の平均値で埋めることもできますが、このデータでは現実的でありません。fillmissing では、時系列を形成する変数については、内挿値または移動ウィンドウ平滑値で埋めることもサポートされます。LotFrontage は時系列ではありません。この変数のデータは断面積データ セットです。

断面積データの欠損値を埋めるためによく使用される方法の 1 つに、回帰モデルを作成して、行の欠損値をその行の欠損値以外のデータから予測する方法があります。簡単な散布図から、敷地の面積とその間口の間に両対数関係があることがわかります。その関係からモデルを作成します。

loglog(housing.LotArea,housing.LotFrontage,'o')

Figure contains an axes object. The axes contains a line object which displays its values using only markers.

その両対数関係を使用して、LotArea に値を回帰させて LotFrontage の欠損値を埋めることができます。

missingValues = ismissing(housing.LotFrontage);
beta = polyfit(log(housing.LotArea(~missingValues)),log(housing.LotFrontage(~missingValues)),1);
housing.LotFrontage(missingValues) = exp(polyval(beta,log(housing.LotArea(missingValues))));

polyfitpolyval など、数値ベクトルを受け入れて table は受け入れない関数を使用するときは、ドット表記を使用して table のデータを操作できます。table はさまざまな型のデータを格納するために設計された "コンテナー" と考えることができます。table には数値以外のデータが含まれることも多いため、数値入力のみに対応する polyfit などの関数は table では機能しません。数値データしか含まれていない場合も、table がコンテナーであることに変わりはありません。関数は table の内容に適用する必要があります。ドット表記を使用して table 変数にアクセスします。

polyfitpolyval で計算した補定された欠損値を散布図に追加します。このデータの実解析には単純補完法では十分でない可能性もありますが、table の数値データを可視化してその計算を行う方法を示します。

hold on
loglog(housing.LotArea(missingValues),housing.LotFrontage(missingValues),'rx')
hold off

Figure contains an axes object. The axes object contains 2 objects of type line. One or more of the lines displays its values using only markers

table 変数の算術演算

ここまで、既存の table 変数の変換、新しい変数の追加、値の代入、プロット、table 変数への polyval のような関数の適用など、さまざまな演算にドット表記を使用してきました。ドット表記は、table 変数の算術演算にも便利です。たとえば、変数 LotFrontage をフィートからメートルに変換します。

housing.LotFrontage = 0.3048 * housing.LotFrontage;
housing.Properties.VariableUnits("LotFrontage") = "m"
housing=2928×24 table
        PID                              MSSubClass                          LotFrontage    LotArea    Neighborhood           BldgType           OverallCond    YearBuilt    YearRemod_Add    Foundation    Heating    CentralAir    FirstFlrArea    SecondFlrArea    LowQualFinishedArea    TotalAboveGroundLivingArea    BsmtFullBath    BsmtHalfBath    FullBath    HalfBath    BedroomAbvGr    GarageType    SalePrice    LastSoldDate
    ____________    _____________________________________________________    ___________    _______    ____________    ______________________    ___________    _________    _____________    __________    _______    __________    ____________    _____________    ___________________    __________________________    ____________    ____________    ________    ________    ____________    __________    _________    ____________

    "0526301100"    1-STORY 1946 & NEWER ALL STYLES                            42.977        31770       NAmes         Single-family Detached         5           1960           1960           CBlock       GasA        true            1656               0                  0                        1656                    1               0             1           0             3           Attchd        2.15e+05      Apr 2010  
    "0526350040"    1-STORY 1946 & NEWER ALL STYLES                            24.384        11622       NAmes         Single-family Detached         6           1961           1961           CBlock       GasA        true             896               0                  0                         896                    0               0             1           0             2           Attchd        1.05e+05      May 2010  
    "0526351010"    1-STORY 1946 & NEWER ALL STYLES                            24.689        14267       NAmes         Single-family Detached         6           1958           1958           CBlock       GasA        true            1329               0                  0                        1329                    0               0             1           1             3           Attchd        1.72e+05      May 2010  
    "0526353030"    1-STORY 1946 & NEWER ALL STYLES                            28.346        11160       NAmes         Single-family Detached         5           1968           1968           CBlock       GasA        true            2110               0                  0                        2110                    1               0             2           1             3           Attchd        2.44e+05      Mar 2010  
    "0527105010"    2-STORY 1946 & NEWER                                       22.555        13830       Gilbert       Single-family Detached         5           1997           1998           PConc        GasA        true             928             701                  0                        1629                    0               0             2           1             3           Attchd       1.899e+05      Feb 2010  
    "0527105030"    2-STORY 1946 & NEWER                                       23.774         9978       Gilbert       Single-family Detached         6           1998           1998           PConc        GasA        true             926             678                  0                        1604                    0               0             2           1             3           Attchd       1.955e+05      May 2010  
    "0527127150"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER      12.497         4920       StoneBr       Townhouse Inside Unit          5           2001           2001           PConc        GasA        true            1338               0                  0                        1338                    1               0             2           0             2           Attchd       2.135e+05      Mar 2010  
    "0527145080"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER      13.106         5005       StoneBr       Townhouse Inside Unit          5           1992           1992           PConc        GasA        true            1280               0                  0                        1280                    0               0             2           0             2           Attchd       1.915e+05      Dec 2009  
    "0527146030"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER      11.887         5389       StoneBr       Townhouse Inside Unit          5           1995           1996           PConc        GasA        true            1616               0                  0                        1616                    1               0             2           0             2           Attchd       2.365e+05      Feb 2010  
    "0527162130"    2-STORY 1946 & NEWER                                       18.288         7500       Gilbert       Single-family Detached         5           1999           1999           PConc        GasA        true            1028             776                  0                        1804                    0               0             2           1             3           Attchd        1.89e+05      May 2010  
    "0527163010"    2-STORY 1946 & NEWER                                        22.86        10000       Gilbert       Single-family Detached         5           1993           1994           PConc        GasA        true             763             892                  0                        1655                    0               0             2           1             3           Attchd       1.759e+05      Mar 2010  
    "0527165230"    1-STORY 1946 & NEWER ALL STYLES                            19.049         7980       Gilbert       Single-family Detached         7           1992           2007           PConc        GasA        true            1187               0                  0                        1187                    1               0             2           0             3           Attchd        1.85e+05      Feb 2010  
    "0527166040"    2-STORY 1946 & NEWER                                       19.202         8402       Gilbert       Single-family Detached         5           1998           1998           PConc        GasA        true             789             676                  0                        1465                    0               0             2           1             3           Attchd       1.804e+05      Apr 2010  
    "0527180040"    1-STORY 1946 & NEWER ALL STYLES                            25.908        10176       Gilbert       Single-family Detached         5           1990           1990           PConc        GasA        true            1341               0                  0                        1341                    1               0             1           1             2           Attchd       1.715e+05      Jan 2010  
    "0527182190"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER      17.465         6820       StoneBr       Townhouse Inside Unit          5           1985           1985           PConc        GasA        true            1502               0                  0                        1502                    1               0             1           1             1           Attchd        2.12e+05      May 2010  
    "0527216070"    2-STORY 1946 & NEWER                                       14.326        53504       StoneBr       Single-family Detached         5           2003           2003           PConc        GasA        true            1690            1589                  0                        3279                    1               0             3           1             4           BuiltIn       5.38e+05      May 2010  
      ⋮

コンテナーである table には乗算を適用できないため、ドット表記を使用することで、housing の table の代わりに、その変数である数値ベクトルの LotFrontage に乗算を適用します。ドット表記を使用して、table から LotFrontage を抽出し、変更後のバージョンを再代入しています。

table の内容にアクセスするもう 1 つの方法として、中かっこを使用して添字を付ける方法があります。これは、中かっこを使用して cell 配列の内容を抽出する方法と同じです。中かっこの添字を使用して、内容を抽出して再挿入することで table のデータの参照と演算を実行できます。たとえば、中かっこの添字を使用して LotFrontage をフィートに変換し直します。

housing{:,"LotFrontage"} = housing{:,"LotFrontage"} / 0.3048;
housing.Properties.VariableUnits("LotFrontage") = "ft";

ドット表記と中かっこの添字では、同じ種類の演算でも構文が異なります。これらはどちらも table の内容に作用します。また、どちらでも table 変数やその行のサブセットを指定できます。

housing.LotArea(1:2)
ans = 2×1

       31770
       11622

housing{1:2,"LotArea"}
ans = 2×1

       31770
       11622

どちらの構文も table の内容に機能しますが、2 つの微妙な違いに注意が必要です。

まず、中かっこの添字には、変数を置換するのではなく、table の内容に代入するという制限があります。たとえば、次の代入では、ドット表記を使用した代入の場合と異なり、変数 LotFrontage のデータ型は変更されません。代入の右辺にある関数 single の呼び出しにより、single データ型の配列が作成されます。ただし、中かっこで housing に添字を付けることで、その配列から既存の table 変数に値を代入しています。ここで、LotFrontage のデータ型は double です。この代入により、右辺の値が double に変換し直されます。

housing{:,"LotFrontage"} = single(housing{:,"LotFrontage"});

2 番目に、中かっこの添字には、ドット表記とは異なり、使い慣れた 2 次元の添字構文を使用できるという利点があります。この構文では、複数の変数を一度に参照でき、行のサブセットも参照できます。たとえば、単位が平方フィートである変数が 5 つあります。それらの変数を一度に 1 つずつ平方メートルに変換するのは手間がかかります。5 つのすべての変数に一度に乗算を適用するには、中かっこの添字を使用します。

areaVars = ["LotArea" "FirstFlrArea" "SecondFlrArea" "LowQualFinishedArea" "TotalAboveGroundLivingArea"];
housing{:,areaVars} = 0.3048^2 * housing{:,areaVars};
housing.Properties.VariableUnits(areaVars) = "m^2";

よくある間違いとして、table の内容に対する演算で、中かっこではなく小かっこの添字が使用されることがあります。table は、ismissingvarfun などの一部の関数では入力として受け入れられますが、算術演算を含む多くの数値演算では受け入れられません。たとえば、小かっこを使用した次の代入はエラーになります。try-catch ブロックでエラーがキャッチされて表示されます。

try
    housing(:,areaVars) = 0.3048^2 * housing(:,areaVars);
catch ME
    disp(ME.message)
end
Undefined function 'mtimes' for input arguments of type 'table'.

この代入がエラーになるのは、housing(:,areaVars) が 2928 行 5 列の table であり、数値行列でないためです。housing{:,areaVars} のように中かっこの添字を使用した場合、結果は 2928 行 5 列の数値行列になります。table は数値以外のデータを含むさまざまな型のデータを格納するように設計されているため、数値データに対してしか意味がない多くの関数は table では機能しません。table のデータにアクセスするための手段として、ドット表記と中かっこの添字を使用できます。

table の数値変数の計算を実行する 3 つ目の方法は、関数 varfun を使用することです。varfun は、中かっこの添字と同様に、table のすべての変数と一部の変数のみの両方を処理できます。中かっことは異なり、varfun は各 table 変数を個別には処理しません。既定では、varfun は、個々の結果ごとに変数を含む別の table を返します。

場合によっては、適用する演算に対応する既存の関数があることがあります。関数を varfun に引数として渡すには、関数ハンドルを使用します。たとえば、関数 round を使用して、areaVars で指定した変数のデータを丸めます。

roundedAreaTable = varfun(@round,housing,"InputVariables",areaVars)
roundedAreaTable=2928×5 table
    round_LotArea    round_FirstFlrArea    round_SecondFlrArea    round_LowQualFinishedArea    round_TotalAboveGroundLivingArea
    _____________    __________________    ___________________    _________________________    ________________________________

        2952                154                      0                        0                              154               
        1080                 83                      0                        0                               83               
        1325                123                      0                        0                              123               
        1037                196                      0                        0                              196               
        1285                 86                     65                        0                              151               
         927                 86                     63                        0                              149               
         457                124                      0                        0                              124               
         465                119                      0                        0                              119               
         501                150                      0                        0                              150               
         697                 96                     72                        0                              168               
         929                 71                     83                        0                              154               
         741                110                      0                        0                              110               
         781                 73                     63                        0                              136               
         945                125                      0                        0                              125               
         634                140                      0                        0                              140               
        4971                157                    148                        0                              305               
      ⋮

目的の処理に一致する関数がない場合は、それを実行する無名関数を記述することもできます。

sqMeters2sqFeet = @(x) x / 0.3048^2;
areaTable = varfun(sqMeters2sqFeet,housing,"InputVariables",areaVars)
areaTable=2928×5 table
    Fun_LotArea    Fun_FirstFlrArea    Fun_SecondFlrArea    Fun_LowQualFinishedArea    Fun_TotalAboveGroundLivingArea
    ___________    ________________    _________________    _______________________    ______________________________

       31770             1656                   0                      0                            1656             
       11622              896                   0                      0                             896             
       14267             1329                   0                      0                            1329             
       11160             2110                   0                      0                            2110             
       13830              928                 701                      0                            1629             
        9978              926                 678                      0                            1604             
        4920             1338                   0                      0                            1338             
        5005             1280                   0                      0                            1280             
        5389             1616                   0                      0                            1616             
        7500             1028                 776                      0                            1804             
       10000              763                 892                      0                            1655             
        7980             1187                   0                      0                            1187             
        8402              789                 676                      0                            1465             
       10176             1341                   0                      0                            1341             
        6820             1502                   0                      0                            1502             
       53504             1690                1589                      0                            3279             
      ⋮

結果は table であるため、小かっこの添字を使用して元の table に再代入できます。

housing(:,areaVars) = areaTable;
housing.Properties.VariableUnits(areaVars) = "ft^2";

2 種類のかっこの違いを理解することが重要です。以下では小かっこが使用されています。

housing(:,areaVars) = areaTable;

以下では中かっこが使用されています。

housing{:,areaVars} = 0.3048^2 * housing{:,areaVars};

2 つの代入の効果は同じです。小かっこを使用した代入では、table を別の table に代入します。中かっこを使用した代入では、値を table の内容に明示的に代入します。その代入の左辺と右辺はどちらも数値行列です。中かっこの添字は、データを抽出して再挿入するため、データを所定の位置で変更するのに適した方法です。内容単位の代入では一度に 1 つのデータ型しか処理できないのに対し、table 単位の代入では異なる型のデータを移動できます。たとえば、次の代入はエラーになります。中かっこの添字で数値データと categorical データが混在しているためです。

try
    housing{:,["LotFrontage" "OverallCond"]} = normalize(housing{:,["LotFrontage" "OverallCond"]});
catch ME
    disp(ME.message)
end
Unable to concatenate the specified table variables.

varfun は table を返すため、小かっこの添字を使用した代入では table 変数の型は変更できません。たとえば、次の代入では、変数のデータ型が double から single に変換されません。

housing(:,areaVars) = varfun(@single,housing,"InputVariables",areaVars);

table 変数のデータ型を変換するには、前述の convertvars を使用します。

table のデータの行演算

中かっこの添字では table から変数を 1 つのデータ型の 1 つの行列として抽出するため、それを使用して table の数値変数の行演算を実行できます。たとえば、データのチェックとして、個々の面積の変数を TotalAboveGroundLivingArea と比較します。中かっこを使用して前者を抽出します。次に、それらの行の合計をドット表記を使用して抽出した TotalAboveGroundLivingArea と比較します。

area = housing{:,["FirstFlrArea" "SecondFlrArea" "LowQualFinishedArea"]}
area = 2928×3

        1656           0           0
         896           0           0
        1329           0           0
        2110           0           0
         928         701           0
         926         678           0
        1338           0           0
        1280           0           0
        1616           0           0
        1028         776           0
      ⋮

isequal(sum(area,2), housing.TotalAboveGroundLivingArea)
ans = logical
   1

面積のデータは一致しています。もう 1 つの例として、4 種類のバスルームのカウントを抽出し、それらを行ごとに集計して、各住宅のバスルームの総数を計算します。

bathCountVars = ["BsmtHalfBath" "HalfBath" "BsmtFullBath" "FullBath"];
bathCounts = housing{:,bathCountVars}
bathCounts = 2928×4

     0     0     1     1
     0     0     0     1
     0     1     0     1
     0     1     1     2
     0     1     0     2
     0     1     0     2
     0     0     1     2
     0     0     0     2
     0     0     1     2
     0     1     0     2
      ⋮

その行列の行の合計を次のように考えるかもしれません。

sum(housing{:,bathCountVars},2);

しかし、その合計は正確ではありません。ハーフバスはフル バスルームの半分としてしかカウントされません。不動産一覧のトレンドとして、複数のハーフバスは小数点以下のカウントで示されます。行列乗算では、その演算を 1 行で記述します。

TotalBaths = housing{:,bathCountVars} * [.1; .1; 1; 1];

新しい変数を table の末尾に追加する代わりに、それらの 4 つの変数を TotalBaths で置換します。この置換で、最初に addvars を使用して既存の変数の隣に TotalBaths を追加します。

housing = addvars(housing,TotalBaths, 'After',"HalfBath");

このデータには 1 つの行に誤りがあります。2007 年に建てられたタウンハウスに、ハーフ バスが 4 つあり、フル バスがないとは考えられません。

groupcounts(housing,"TotalBaths")
ans=17×3 table
    TotalBaths    GroupCount    Percent 
    __________    __________    ________

       0.4             1        0.034153
         1           442          15.096
       1.1           293          10.007
       1.2            20         0.68306
       1.3             2        0.068306
         2           890          30.396
       2.1           558          19.057
       2.2            29         0.99044
         3           349          11.919
       3.1           288          9.8361
       3.2             6         0.20492
       3.3             1        0.034153
         4            25         0.85383
       4.1            16         0.54645
       4.2             3         0.10246
         6             2        0.068306
      ⋮

housing(housing.TotalBaths < 1,:)
ans=1×25 table
        PID                              MSSubClass                          LotFrontage    LotArea    Neighborhood          BldgType           OverallCond    YearBuilt    YearRemod_Add    Foundation    Heating    CentralAir    FirstFlrArea    SecondFlrArea    LowQualFinishedArea    TotalAboveGroundLivingArea    BsmtFullBath    BsmtHalfBath    FullBath    HalfBath    TotalBaths    BedroomAbvGr    GarageType    SalePrice    LastSoldDate
    ____________    _____________________________________________________    ___________    _______    ____________    _____________________    ___________    _________    _____________    __________    _______    __________    ____________    _____________    ___________________    __________________________    ____________    ____________    ________    ________    __________    ____________    __________    _________    ____________

    "0528228275"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER        53          3922        Blmngtn       Townhouse Inside Unit         5           2006           2007           PConc        GasA        true            1402              0                   0                        1402                    0               2             0           2           0.4             2            Attchd      1.942e+05      Jan 2007  

BsmtHalfBath のカウントは、フル バスルームが 2 つの誤りではないかと考えられます。バスルームのカウントはいずれも数値です。中かっこによる代入で、その行の 3 つの値をすべて更新します。

housing{housing.TotalBaths < 1,["BsmtHalfBath" "FullBath" "TotalBaths"]} = [0 2 2.2];

次に、removevars を使用して重複する元の変数を削除します。

housing = removevars(housing,bathCountVars)
housing=2928×21 table
        PID                              MSSubClass                          LotFrontage    LotArea    Neighborhood           BldgType           OverallCond    YearBuilt    YearRemod_Add    Foundation    Heating    CentralAir    FirstFlrArea    SecondFlrArea    LowQualFinishedArea    TotalAboveGroundLivingArea    TotalBaths    BedroomAbvGr    GarageType    SalePrice    LastSoldDate
    ____________    _____________________________________________________    ___________    _______    ____________    ______________________    ___________    _________    _____________    __________    _______    __________    ____________    _____________    ___________________    __________________________    __________    ____________    __________    _________    ____________

    "0526301100"    1-STORY 1946 & NEWER ALL STYLES                               141        31770       NAmes         Single-family Detached         5           1960           1960           CBlock       GasA        true            1656               0                  0                        1656                    2             3           Attchd        2.15e+05      Apr 2010  
    "0526350040"    1-STORY 1946 & NEWER ALL STYLES                                80        11622       NAmes         Single-family Detached         6           1961           1961           CBlock       GasA        true             896               0                  0                         896                    1             2           Attchd        1.05e+05      May 2010  
    "0526351010"    1-STORY 1946 & NEWER ALL STYLES                                81        14267       NAmes         Single-family Detached         6           1958           1958           CBlock       GasA        true            1329               0                  0                        1329                  1.1             3           Attchd        1.72e+05      May 2010  
    "0526353030"    1-STORY 1946 & NEWER ALL STYLES                                93        11160       NAmes         Single-family Detached         5           1968           1968           CBlock       GasA        true            2110               0                  0                        2110                  3.1             3           Attchd        2.44e+05      Mar 2010  
    "0527105010"    2-STORY 1946 & NEWER                                           74        13830       Gilbert       Single-family Detached         5           1997           1998           PConc        GasA        true             928             701                  0                        1629                  2.1             3           Attchd       1.899e+05      Feb 2010  
    "0527105030"    2-STORY 1946 & NEWER                                           78         9978       Gilbert       Single-family Detached         6           1998           1998           PConc        GasA        true             926             678                  0                        1604                  2.1             3           Attchd       1.955e+05      May 2010  
    "0527127150"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER          41         4920       StoneBr       Townhouse Inside Unit          5           2001           2001           PConc        GasA        true            1338               0                  0                        1338                    3             2           Attchd       2.135e+05      Mar 2010  
    "0527145080"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER          43         5005       StoneBr       Townhouse Inside Unit          5           1992           1992           PConc        GasA        true            1280               0                  0                        1280                    2             2           Attchd       1.915e+05      Dec 2009  
    "0527146030"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER          39         5389       StoneBr       Townhouse Inside Unit          5           1995           1996           PConc        GasA        true            1616               0                  0                        1616                    3             2           Attchd       2.365e+05      Feb 2010  
    "0527162130"    2-STORY 1946 & NEWER                                           60         7500       Gilbert       Single-family Detached         5           1999           1999           PConc        GasA        true            1028             776                  0                        1804                  2.1             3           Attchd        1.89e+05      May 2010  
    "0527163010"    2-STORY 1946 & NEWER                                           75        10000       Gilbert       Single-family Detached         5           1993           1994           PConc        GasA        true             763             892                  0                        1655                  2.1             3           Attchd       1.759e+05      Mar 2010  
    "0527165230"    1-STORY 1946 & NEWER ALL STYLES                            62.496         7980       Gilbert       Single-family Detached         7           1992           2007           PConc        GasA        true            1187               0                  0                        1187                    3             3           Attchd        1.85e+05      Feb 2010  
    "0527166040"    2-STORY 1946 & NEWER                                           63         8402       Gilbert       Single-family Detached         5           1998           1998           PConc        GasA        true             789             676                  0                        1465                  2.1             3           Attchd       1.804e+05      Apr 2010  
    "0527180040"    1-STORY 1946 & NEWER ALL STYLES                                85        10176       Gilbert       Single-family Detached         5           1990           1990           PConc        GasA        true            1341               0                  0                        1341                  2.1             2           Attchd       1.715e+05      Jan 2010  
    "0527182190"    1-STORY PUD (Planned Unit Development) - 1946 & NEWER      57.299         6820       StoneBr       Townhouse Inside Unit          5           1985           1985           PConc        GasA        true            1502               0                  0                        1502                  2.1             1           Attchd        2.12e+05      May 2010  
    "0527216070"    2-STORY 1946 & NEWER                                           47        53504       StoneBr       Single-family Detached         5           2003           2003           PConc        GasA        true            1690            1589                  0                        3279                  4.1             4           BuiltIn       5.38e+05      May 2010  
      ⋮

中かっことは異なり、varfun は table の各変数を個別には処理しません。そのため、varfun では行演算は実行できません。関連する関数の rowfun では行演算が "可能" です。多くの場合、行演算には中かっこの添字を使用した方が簡単で高速です。

table のデータのリダクション

これまでの節では、table の数値データの演算として、元の値を置換する "変換" を見てきました。それ以外の重要な演算で多いのは、結果がスカラーである "リダクション" です。たとえば、SalePrice の値から価格の中央値を計算します。

median(housing.SalePrice)
ans = 160000

関数 median は行列を列方向に処理します。中かっこの添字を使用して、それらの 4 つの変数を数値行列として抽出できます。その後、行列の列の中央値を計算できます。

median(housing{:,["LotFrontage", "LotArea" "TotalAboveGroundLivingArea" "SalePrice"]})
ans = 1×4
105 ×

    0.0007    0.0944    0.0144    1.6000

この演算は、変数名や table のその他のメタデータを結果に付加しません。代替方法として、varfun を使用して table の各変数に median を適用できます。varfun の結果は個別の数値結果を含む別の table となり、名前が維持されます。

varfun(@median,housing,"InputVariables",["LotFrontage", "LotArea" "TotalAboveGroundLivingArea" "SalePrice"])
ans=1×4 table
    median_LotFrontage    median_LotArea    median_TotalAboveGroundLivingArea    median_SalePrice
    __________________    ______________    _________________________________    ________________

          69.183              9436.5                      1442                       1.6e+05     

これらの 2 つは、どちらも中央値を取得する等価な方法です。変数名を別の table で維持するか、結果を 1 つの数値行ベクトルにするか、トレードオフの関係にあります。どちらの方法を選択するかは、結果をどのように扱うかに応じて決定します。

混在するデータ型の演算

中央値の計算に中かっこを使用する場合、もう 1 つ欠点があります。中かっこを使用するには、すべての変数が互換性のあるデータ型である必要があります。つまり、変数から抽出するデータは 1 つの行列に連結できるデータ型でなければなりません。順序 categorical データにも中央値があります。categorical 配列と数値配列は連結できないため、次の演算はエラーになります。

median(housing{:,["LotFrontage", "LotArea" "OverallCond" "TotalAboveGroundLivingArea" "SalePrice"]})

一方、varfun は table の各変数を個別に処理するため、変数が同じデータ型または連結可能な互換性のある型である必要はありません。唯一の要件は、適用される関数をすべての変数がサポートしていることです。順序 categorical 変数と数値変数の中央値を 1 つの関数呼び出しで計算するには、varfun を使用します。

varfun(@median,housing,"InputVariables",["LotFrontage", "LotArea" "OverallCond" "TotalAboveGroundLivingArea" "SalePrice"])
ans=1×5 table
    median_LotFrontage    median_LotArea    median_OverallCond    median_TotalAboveGroundLivingArea    median_SalePrice
    __________________    ______________    __________________    _________________________________    ________________

          69.183              9436.5                5                           1442                       1.6e+05     

参考

| | | | | | | | | | | |

関連するトピック