setvaropts
Set variable import options
Syntax
opts = setvaropts(opts,Name,Value)
opts = setvaropts(opts,selection,Name,Value)
Description
updates all the variables in theopts
= setvaropts(opts
,Name,Value
)opts
object based on the specifications in theName,Value
arguments.
updates and returns anopts
= setvaropts(opts
,selection
,Name,Value
)opts
object for the variables specified in theselection
argument, based on the specifications in theName,Value
arguments.
Examples
Set Options for Selected Variables
创建一个对象导入选项,设置选项or selected variables, and import the data using the tailored options and thereadtable
function.
Create an options object for the spreadsheetpatients.xls
.
opts = detectImportOptions('patients.xls');
Set theFillValue
property for theSmoker
,Diastolic
, andSystolic
variables.
opts = setvaropts(opts,'Smoker','FillValue',false); opts = setvaropts(opts,{'Diastolic','Systolic'},'FillValue',0);
Select the variables you want to import.
opts.SelectedVariableNames = {'Smoker','Diastolic','Systolic'};
Import the variables and display a summary.
T = readtable('patients.xls',opts); summary(T)
Variables: Smoker: 100x1 logical Values: True 34 False 66 Diastolic: 100x1 double Values: Min 68 Median 81.5 Max 99 Systolic: 100x1 double Values: Min 109 Median 122 Max 138
Set Options for Numeric Data Containing Missing or Incomplete Records
Importing data that has missing or incomplete fields requires recognizing the missing instances and deciding how the missing instances will be imported. UseimportOptions
to capture both these decisions and fetch the data usingreadtable
.
Create an import options object for the file, update properties that control the import of missing data, usereadtable
to import the data. Note that the datasetairlinesmall.csv
has two numeric variablesArrDelay
andDepDelay
, that contain missing data indicated byNA
.
Create an import options object from the file.
opts = detectImportOptions('airlinesmall.csv');
Use theTreatAsMissing
property to specify the characters in the data that are place holders for missing instances. In this example, the two numeric variablesArrDelay
andDepDelay
contain missing fields that contain the textNA
.
opts = setvaropts(opts,{'ArrDelay','DepDelay'},'TreatAsMissing','NA');
Specify the action for the importing function to take when importing missing instances. SeeImportOptions
properties page for more options.
opts.MissingRule ='fill';
Specify the value to use when the importing function finds a missing instance. Here the missing instances in variablesArrDelay
andDepDelay
are replaced by0
.
opts = setvaropts(opts,{'ArrDelay','DepDelay'},'FillValue',0);
Select the variables you want to work with and import them usingreadtable
.
opts.SelectedVariableNames = {'ArrDelay','DepDelay'}; T = readtable('airlinesmall.csv',opts);
Examine the values inArrDelay
andDepDelay
. Verify that the importing function replaced the missing values denoted byNA
.
T(166:180,:)
ans=15x2 tableArrDelay DepDelay ________ ________ - 105 - 1 0 10211 0 0 0 -1 0 0 0 1 0 1 0 14 0 -14 0 5 0 25 38 0 -5 0 0 6 0
Set Options When Importing Text Data
Use thesetvaropts
function to update properties that control the import of text data. First, get the import options object for the file. Next, examine and update the options for the text variables. Finally, import the variables using thereadtable
function.
Preview the data inpatients.xls
. Notice the text data in the columnLastName
. Only a preview of the first 10 rows is shown here.
Get the import options object.
opts = detectImportOptions('patients.xls');
Get and examine theVariableImportOptions
for variableLastName
.
getvaropts(opts,'LastName')
ans = TextVariableImportOptions with properties: Variable Properties: Name: 'LastName' Type: 'char' FillValue: '' TreatAsMissing: {} QuoteRule: 'remove' String Options: WhitespaceRule: 'trim'
Set the data type of the variable tostring
.
opts = setvartype(opts,'LastName','string');
Set theFillValue
property of the variable to replace missing values with'NoName'
.
opts = setvaropts(opts,'LastName','FillValue','NoName');
Select, read, and display a preview of the first 10 rows of the variable.
opts.SelectedVariableNames ='LastName'; T = readtable('patients.xls',opts); T.LastName(1:10)
ans =10x1 string array"Smith" "Johnson" "Williams" "Jones" "Brown" "Davis" "Miller" "Wilson" "Moore" "Taylor"
Set Options When Importing Logical Data
Use thesetvaropts
function to update properties that control the import oflogical
数据。首先,导入选项对象file. Next, examine and update the options for the logical variables. Finally, import the variables using thereadtable
function.
Preview the data inairlinesmall_subset.xlsx
. Notice the logical data in the columnCancelled
. Only a preview of rows 30 to 40 is shown here.
Get the import options object.
opts = detectImportOptions('airlinesmall_subset.xlsx');
Get and examine theVariableImportOptions
for variableCancelled
.
getvaropts(opts,'Cancelled')
ans = NumericVariableImportOptions with properties: Variable Properties: Name: 'Cancelled' Type: 'double' FillValue: NaN TreatAsMissing: {} QuoteRule: 'remove' Numeric Options: ExponentCharacter: 'eEdD' DecimalSeparator: '.' ThousandsSeparator: ''
Set the data type of the variable tological
.
opts = setvartype(opts,'Cancelled','logical');
Set theFillValue
property of the variable to replace missing values withtrue
.
opts = setvaropts(opts,'Cancelled','FillValue',true);
Select, read, and display a summary of the variable.
opts.SelectedVariableNames ='Cancelled'; T = readtable('airlinesmall_subset.xlsx',opts); summary(T)
Variables: Cancelled: 1338x1 logical Values: True 29 False 1309
Importing Date and Time Data
UseDatetimeVariableImportOptions
properties to control the import ofdatetime
数据。First, get theImportOptions
object for the file. Next, examine and update theVariableImportOptions
for the datetime variables. Finally, import the variables usingreadtable
.
Preview of data inoutages.csv
. Notice the date and time data in the columnsOutageTime
andRestorationTime
. Only the first 10 rows are shown here.
Get the import options object.
opts = detectImportOptions('outages.csv');
Get and examine theVariableImportOptions
for datetime variablesOutageTime
andRestorationTime
.
varOpts = getvaropts(opts,{'OutageTime','RestorationTime'})
varOpts = 1x2 DatetimeVariableImportOptions array with properties: DatetimeFormat DatetimeLocale InputFormat Type FillValue TimeZone Name QuoteRule TreatAsMissing
Set theFillValue
property of the variables to replace missing values with current date and time.
opts = setvaropts(opts,{'OutageTime','RestorationTime'},...'FillValue','now');
Select, read, and preview the two variables. Notice the missing value in the second row ofRestorationTime
has been filled with current date and time.
opts.SelectedVariableNames = {'OutageTime','RestorationTime'}; T = readtable('outages.csv',opts); T(1:10,:)
ans=10x2 table nullOutageTime RestorationTime ____________________ ____________________ 01-Feb-2002 12:18:00 07-Feb-2002 16:50:00 23-Jan-2003 00:49:00 19-Sep-2017 18:29:43 07-Feb-2003 21:15:00 17-Feb-2003 08:14:00 06-Apr-2004 05:44:00 06-Apr-2004 06:10:00 16-Mar-2002 06:18:00 18-Mar-2002 23:23:00 18-Jun-2003 02:49:00 18-Jun-2003 10:54:00 20-Jun-2004 14:39:00 20-Jun-2004 19:16:00 06-Jun-2002 19:28:00 07-Jun-2002 00:51:00 16-Jul-2003 16:23:00 17-Jul-2003 01:12:00 27-Sep-2004 11:09:00 27-Sep-2004 16:37:00
Set Options When Importing Categorical Data
Use thesetvaropts
function to update properties that control the import ofcategorical
数据。首先,导入选项对象file. Next, examine and update the options for the categorical variables. Finally, import the variables using thereadtable
function.
Preview the data inoutages.csv
. Notice the categorical data in the columnsRegion
andCause
. This table shows only the first 10 rows.
Get the import options object.
opts = detectImportOptions('outages.csv');
Get and examine the options for variablesRegion
andCause
.
getvaropts(opts,{'Region','Cause'})
ans = 1x2 TextVariableImportOptions array with properties: WhitespaceRule Type FillValue Name QuoteRule TreatAsMissing
Set the data type of the variables tocategorical
.
opts = setvartype(opts,{'Region','Cause'},'categorical');
Set theFillValue
property of the variables to replace missing values with category name'Miscellaneous'
. SetTreatAsMissing
property to'unknown'
.
opts = setvaropts(opts,{'Region','Cause'},...'FillValue','Miscellaneous',...'TreatAsMissing','unknown');
Select, read, and display a summary of the two variables.
opts.SelectedVariableNames = {'Region','Cause'}; T = readtable('outages.csv',opts); summary(T)
Variables: Region: 1468x1 categorical Values: MidWest 142 NorthEast 557 SouthEast 389 SouthWest 26 West 354 Cause: 1468x1 categorical Values: Miscellaneous 24 attack 294 earthquake 2 energy emergency 188 equipment fault 156 fire 25 severe storm 338 thunder storm 201 wind 95 winter storm 145
Input Arguments
opts
—File import options
SpreadsheetImportOptions
|DelimitedtextImportOptions
|FixedWidthImportOptions
File import options, specified as aSpreadsheetImportOptions
,DelimitedTextImportOptions
, or aFixedWidthImportOptions
object created by thedetectImportOptions
function. Theopts
object contains properties that control the data import process, such as variable properties, data location properties, replacement rules, and others.
selection
—Selected variables
character vector|cell array of character vector|array of indices
Selected variables, specified as a character vector, cell array of character vectors, or an array of numeric indices.
变量名(或指标)必须的一个子集e names contained in theVariableNames
property of theopts
object.
Example:'Height'
Example:{'Height','LastName'}
Example:[5 9]
Data Types:char
|cell
|uint64
Name-Value Pair Arguments
Specify optional comma-separated pairs ofName,Value
arguments.Name
is the argument name andValue
is the corresponding value.Name
must appear inside single quotes (' '
). You can specify several name and value pair arguments in any order asName1,Value1,...,NameN,ValueN
.
opts = setvaropts(opts,'Weight','FillValue',0)
sets theFillValue
for the variableWeight
to0
.
Common Options
'FillValue'
—Replacement value for missing data
character vector|scalar numeric value|true
|false
Replacement value for missing data, depending on the type of the variable, specified as a character vector, a scalar numeric, or a logical valuetrue
orfalse
.
Type of Variable | Description |
---|---|
Text | Character vector containing the replacement text Example: |
Numeric | Scalar numeric to replace missing instances The importing function converts the input for Example: |
Logical | Character vector containing Example: |
Datetime | Character vector or a scalar value representing date and time data. For more information on valid Example: Example: |
Categorical | Character vector containing the name to use for the replacement category. Example: |
To direct the import of data that is missing, unconvertible, or that causes errors, use these four properties together:FillValue
,TreatAsMissing
,MissingRule
, andErrorRule
. The importing function uses the value specified in theFillValue
property when:
Data is unconvertible or matches a value in
TreatAsMissing
.MissingRule
or theErrorRule
is set tofill
.
'TreatAsMissing'
—Text to interpret as missing data
character vector|cell array of character vectors
Text to interpret as missing data, specified as a character vector or a cell array of character vectors.
When the importing function finds missing instances, it uses the specification in theMissingRule
property to determine the appropriate action.
Example:'TreatAsMissing',{'NA','TBD'}
instructs the importing function to treat any occurrence ofNA
orTBD
as a missing fields.
Data Types:char
|cell
'QuoteRule'
—Procedure to manage double quotation marks
'remove'
|'keep'
|'error'
Procedure to manage double quotation marks in the data, specified as one of the values in this table.
Quote Rule | Process |
---|---|
'remove' |
If double quotes ( Example: If two sets of double quotes ( Example: If a pair of opening and closing quotes surrounding characters is followed by a single lone unpaired double quotes, then the importing function ignores the lone unpaired double quote. Example: |
'keep' |
Retain all quotation marks. |
'error' |
Report an error when converting data which begins with a double quotation mark (" ). Use this setting if the field should never be quoted. |
Example:If the'QuoteRule'
is set to'remove'
, then the importing function imports"abc"def"
as六边形abcdef”
.
Text Only
'WhiteSpaceRule'
—Procedure to manage leading and trailing white spaces
'trim'
(default) |'trimleading'
|'trimtrailing'
|'preserve'
Procedure to manage leading and trailing white spaces when importing text data, specified as one of the values in the table.
White Space Rule | Process |
---|---|
'trim' |
Remove any leading or trailing white spaces from the text. Interior white space is unaffected. Example: |
'trimleading' |
Remove only the leading white spaces. Example: |
'trimtrailing' |
Remove only the trailing white spaces. Example: |
'preserve' |
Preserve white spaces. Example: |
Numeric Only
'ExponentCharacter'
—Characters indicating exponent
character vector
Characters indicating the exponent, specified as a character vector. The importing function uses theExponentCharacter
property to recognize the characters indicating the exponent for a number expressed in the scientific notation.
Example:IfvarOpts.ExponentCharacter = 'a'
, then the importing function imports the text"1.2a3"
as the number1200
.
'DecimalSeparator'
—Characters indicating decimal separator
character vector
Characters indicating the decimal separator, specified as a character vector. The importing function uses theDecimalSeparator
property to distinguish the integer part of a number from the decimal part.
When converting to integer data types, numbers with a decimal part are rounded to the nearest integer.
Example:IfvarOpts.DecimalSeparator = ','
, then the importing function imports the text"3,14159"
as the number3.14159
.
'ThousandsSeparator'
—Characters that indicate the thousands grouping
character vector
Characters that indicate the thousands grouping, specified as a character vector. The thousands grouping characters act as visual separators, grouping the number at every three place values. The importing function uses the characters in theThousandsSeparator
property to interpret the numbers being imported.
Example:IfvarOpts.ThousandsSeparator = ','
, then the importing function imports the text"1,234,000"
as1234000
.
Logical Only
'TrueSymbols'
—Text to treat as logical valuetrue
character vector|cell array of character vectors
Text to treat as the logical valuetrue
, specified as a character vector or a cell array of character vectors.
Example:IfvarOpts.TrueSymbols = {'t','TRUE'}
, then the importing function imports any fields containingt
orTRUE
as the logical valuetrue
.
Data Types:char
|cell
'FalseSymbols'
—Text to treat as logical valuefalse
character vector|cell array of character vectors
Text to treat as the logical valuefalse
, specified as a character vector or a cell array of character vectors.
Example:IfvarOpts.FalseSymbols = {'f','FALSE'}
, then the importing function imports any fields containingf
orFALSE
as the logical valuefalse
.
Data Types:char
|cell
'CaseSensitive'
—Indicator to match case
true
|false
Indicator to match case, specified as a logical valuetrue
orfalse
.
To interpret the input data as missing,true
, orfalse
, the importing function matches the data to values specified inTreatAsMissing
,TrueSymbols
, andFalseSymbols
.
Datetime Only
'DatetimeFormat'
—Display format
'default'
|'defaultdate'
|'preserveinput'
|custom format|character vector
Display format, specified as a character vector. TheDatetimeFormat
property controls the display format of dates and times in the output. SpecifyDatetimeFormat
as one of these values.
Value ofDatetimeFormat |
Description |
---|---|
|
Use the default display format. |
|
Use the default display format for datetime values created without time components. |
|
Use the format specified by the input format, |
Custom formats | Use the letters |
The factory default format depends on your system locale. To change the default display format, seeDefault datetime Format.
'InputFormat'
—Format of input text representing dates and times
character vector
Format of the input text representing dates and times, specified as a character vector that contains letter identifiers.
This table shows several common input formats and examples of the formatted input for the date, Saturday, April 19, 2014 at 9:41:06 PM in New York City.
Value ofInputFormat |
Example |
---|---|
'yyyy-MM-dd' |
2014-04-19 |
'dd/MM/yyyy' |
19/04/2014 |
'dd.MM.yyyy' |
19.04.2014 |
“yyyy年MM月dd日” |
2014年 04月 19日 |
'MMMM d, yyyy' |
April 19, 2014 |
'eeee, MMMM d, yyyy h:mm a' |
Saturday, April 19, 2014 9:41 PM |
'MMMM d, yyyy HH:mm:ss Z' |
April 19, 2014 21:41:06 -0400 |
'yyyy-MM-dd''T''HH:mmXXX' |
2014-04-19T21:41-04:00 |
For a complete list of valid letter identifiers, see theFormat
property for datetime arrays.
Example:'InputFormat','eeee, MMMM d, yyyy HH:mm:ss'
'DatetimeLocale'
—Locale to use for interpreting dates
character vector
Locale to use for interpreting dates, specified as a character vector. TheDatetimeLocale
value determines how the importing function interprets text that represents dates and times.
Set theDatetimeLocale
value to:
'system'
, to specify your system locale.or a character vector in the form
, wherexx
_YY
xx
is a lowercase ISO 639-1 two-letter code that specifies a language, andYY
is an uppercase ISO 3166-1 alpha-2 code that specifies a country.
This table lists some common values for the locale.
Locale | Language | Country |
---|---|---|
'de_DE' |
German | Germany |
'en_GB' |
English | United Kingdom |
'en_US' |
English | United States |
'es_ES' |
Spanish | Spain |
'fr_FR' |
French | France |
'it_IT' |
Italian | Italy |
'ja_JP' |
Japanese | Japan |
'ko_KR' |
Korean | Korea |
'nl_NL' |
Dutch | Netherlands |
'zh_CN' |
Chinese (simplified) | China |
Example:varOpts.DatetimeLocale = 'de_DE'
sets the date time locale to German.
Note
TheLocale
value determines how input values are interpreted. The display format and language is specified by theLocaleoption in theDatetime formatsection of the Preferences panel. To change the default datetime locale, seeSet Command Window Preferences.
Categorical Only
'Categories'
—Expected categories
cell array of character vectors
Expected categories, specified as a cell array of character vectors, containing a list of category names.
Names in the input fields must match one of the names specified in theCategories
property to avoid a conversion error.
Example:varOpts.Categories = {'BareLand','Forest','Water','Roads','Buildings'};
'Protected'
—Category protection indicator
false
|true
|0
|1
Category protection indicator, specified as eitherfalse
,true
,0
, or1
. The categories of ordinal categorical arrays are always protected. If theOrdinal
property is set totrue
, then the default value forProtected
istrue
. Otherwise, the value forProtected
isfalse
. For more information on categorical arrays, see thecategorical
function reference page.
'Ordinal'
—Mathematical ordering indicator
false
(default) |true
|0
|1
Mathematical ordering indicator, specified as eitherfalse
,true
,0
, or1
. For more information on categorical arrays, see thecategorical
function reference page.
See Also
Introduced in R2016b
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select:.
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina(Español)
- Canada(English)
- United States(English)
Europe
- Belgium(English)
- Denmark(English)
- Deutschland(Deutsch)
- España(Español)
- Finland(English)
- France(Français)
- Ireland(English)
- Italia(Italiano)
- Luxembourg(English)
- Netherlands(English)
- Norway(English)
- Österreich(Deutsch)
- Portugal(English)
- Sweden(English)
- Switzerland
- United Kingdom(English)