简体   繁体   中英

How to delete every 2nd column of 2 columns in a dataset in R

I have a dataset which is something like this

       USA x.1 Canada x.2 China x.3 Russia x.4 Germany x.5
data   12  34   34    45    34   67   56    45    45    56

I want to delete all the columns with the column name x.1, x.2 and so on. how can i do this in R via subset

Probably the shortest way to achieve this is:

df <- df[c(T,F)]
#     USA Canada China Russia Germany
#data  12     34    34     56      45

The vector c(TRUE,FALSE) [abbreviated here as c(T,F) ] is recycled, leading to an alternating series of TRUE, FALSE, TRUE, FALSE etc. Thereby, every second column is removed.

只需选择您要保留的列:

df <- df[,seq(1,ncol(df),2)]

您可以使用正则表达式。

df[,!grepl("^x\\.[[:digit:]]+$",colnames(df))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM