Our World Statistics Day conversations have been a great reminder of how much statistics can inform our lives. Do you have an example of how statistics has made a difference in your life? Share your story with the Community!
Choose Language Hide Translation Bar
Highlighted
Level II

## Deleting multiple columns based on column name

Hi ,

I want to delete multiple columns based on some specific strings they contain in column name. I can do it for single name. But for multiple name it does not work.

col_list = dt << get column names(string);

for (i = nitems(col_list), i > 0, i--,
if (contains(col_list[i], "SAVED_IMAGES", "sw_", "HH"),
remove from(col_list, i);
);
);

Shows this error

dt = Current Data Table();
col_list = dt << get column names( string );
For( i = N Items( col_list ), i > 0, i--,
If( Contains( col_list[i], "SAVED_IMAGES", "SS_EID" ),

Remove From( col_list, i )
)
);

1 ACCEPTED SOLUTION

Accepted Solutions
Highlighted
Level VII

## Re: Deleting multiple columns based on column name

If I understand your question you want to iterate through both the column names and the strings to match:

``````col_list = dt << get column names(string);

remove_strings = {"SAVED_IMAGES", "sw_", "HH"};

//for each column name
for (i = nitems(col_list), i > 0, i--,

//for each string to match
for( j = 1, j <= N Items( remove_strings ), j++,

//if it matches remove the item
if( contains( col_list[i], remove_strings[j] ) > 0,
remove from(col_list, i);
);
);
);``````
4 REPLIES 4
Highlighted
Super User

## Re: Deleting multiple columns based on column name

I believe the structure you need to use for your comparison is:

``````if (contains(col_list[i], "SAVED_IMAGES") & contains(col_list[i], "sw_")  &
contains(col_list[i], "HH"),
``````
Jim
Highlighted
Level VII

## Re: Deleting multiple columns based on column name

If I understand your question you want to iterate through both the column names and the strings to match:

``````col_list = dt << get column names(string);

remove_strings = {"SAVED_IMAGES", "sw_", "HH"};

//for each column name
for (i = nitems(col_list), i > 0, i--,

//for each string to match
for( j = 1, j <= N Items( remove_strings ), j++,

//if it matches remove the item
if( contains( col_list[i], remove_strings[j] ) > 0,
remove from(col_list, i);
);
);
);``````
Highlighted
Level II

## Re: Deleting multiple columns based on column name

This script deletes  columns that contain those names in columns. What should I do if I want to keep only

those specific coulmns (contains those names) and delete other columns?

Highlighted
Super User

## Re: Deleting multiple columns based on column name

Here is how I would do it

``````col_list = dt << get column names( string );

For( i = N Items( col_list ), i > 0, i--,
If(
Not(
Contains( col_list[i], "SAVED_IMAGES" ) | Contains( col_list[i], "sw_" ) |
Contains( col_list[i], "HH" )
),
Remove From( col_list, i )
)
);``````
Jim
Article Labels

There are no labels assigned to this post.