ROY ROY - 2 months ago 6
R Question

Selecting specific columns from dataset

I have a dataset which looks this this:

A B X50_TT_1.0 X50_TT_1.1 X60_DD_2.0 X60_DD_2.1 X100_L2V_7.0 X100_L2V_7.1
3 1 1 0 0 1 1 0
6 3 0 1 0 1 0 1
2 3 1 0 0 1 1 0
10 5 0 1 1 0 1 0
0 0 1 0 1 0 0 1


I want to have new data frame (df) which only contains columns which ends with 1.1, 2.1 i.e.

df

X50_TT_1.1 X60_DD_2.1 X100_L2V_7.1
0 1 0
1 1 1
0 1 0
1 0 0
0 0 1


As here I only shows few columns but actually it contains more than 100 columns. Therefore, kindly provide the solution which can be applicable to as many columns dataset consists.

Thanks in advance.

Answer

I guess the pattern is, that the column ends on ".1" may you need to adapt it at that point. My data I am using

    original_data
  A B X50_TT_1.0 X50_TT_1.1 X60_DD_2.0 X60_DD_2.1 X100_L2V_7.0 X100_L2V_7.1
1 3 1          1          0          0          1            1            0

Actually this is for everything ending with "1"

df <- original_data[which(grepl(".1$", names(original_data)))]

For ending with ".1" you have to use:

df <- original_data[which(grepl("\\.1$", names(original_data)))]

For original_data both gave me the same result:

    df
  X50_TT_1.1 X60_DD_2.1 X100_L2V_7.1
1          0          1            0
Comments