从R中的数据框中提取具有相同标题的变量

时间:2023-01-22 22:56:19

I have a huge data set. Here is an example:

我有一个庞大的数据集。这是一个例子:

Ac.1<-rnorm(100, 0, 1)
At.2<-rnorm(100, 0, 1)
Ae.3<-rnorm(100, 0, 1)
Ba.1<-rnorm(100, 0, 1)
Bc.2<-rnorm(100, 0, 1)
Be.3<-rnorm(100, 0, 1)
Cb.1<-rnorm(100, 0, 1)
Cy.2<-rnorm(100, 0, 1)
Cc.3<-rnorm(100, 0, 1)

The current data set looks like:

当前数据集如下所示:

current.df<-data.frame(Ac.1,Ae.3,Ba.1,At.2,Bc.2,Cb.1,Cy.2,Be.3,Cc.3)

I want to create the small date frame that has the same title of "B", namedsmall.df. It should look like

我想创建具有相同标题“B”,namedsmall.df的小日期框架。应该是这样的

name(small.df)
[1] "Ba.1" "Bc.2" "Be.3"

2 个解决方案

#1


0  

You can perform the desired process by selecting your letter.
You can use a combination of assign & regexpr to find your col and assign the final DF :

您可以通过选择您的信件来执行所需的过程。您可以使用assign和regexpr的组合来查找col并分配最终的DF:

#Chose your Letter
 letter <- "B"

#Find columns in colnames with a regexpr
cols <- which(regexpr(paste0("^",letter),names(current.df)) != -1)

#Assign a letter variable dependant name to your new DF
assign(paste0(letter,".small.df"),current.df[,cols])

Hope that wil helps

希望对你有所帮助

Gottavianoni

#2


0  

You can do this to select the columns.

您可以这样做以选择列。

small.df <- current.df[, c("Ba.1", "Bc.2", "Be.3")]

Or this to select all the columns began with "B".

或者这样选择以“B”开头的所有列。

small.df <- current.df[, grepl("^B", names(current.df))]

#1


0  

You can perform the desired process by selecting your letter.
You can use a combination of assign & regexpr to find your col and assign the final DF :

您可以通过选择您的信件来执行所需的过程。您可以使用assign和regexpr的组合来查找col并分配最终的DF:

#Chose your Letter
 letter <- "B"

#Find columns in colnames with a regexpr
cols <- which(regexpr(paste0("^",letter),names(current.df)) != -1)

#Assign a letter variable dependant name to your new DF
assign(paste0(letter,".small.df"),current.df[,cols])

Hope that wil helps

希望对你有所帮助

Gottavianoni

#2


0  

You can do this to select the columns.

您可以这样做以选择列。

small.df <- current.df[, c("Ba.1", "Bc.2", "Be.3")]

Or this to select all the columns began with "B".

或者这样选择以“B”开头的所有列。

small.df <- current.df[, grepl("^B", names(current.df))]