Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing column names of a data frame by changing values - R

Tags:

dataframe

r

Let I have the below data frame.

df.open<-c(1,4,5)
df.close<-c(2,8,3)

df<-data.frame(df.open, df.close)



> df
  df.open df.close
1       1        2
2       4        8
3       5        3

I wanto change column names which includes "open" with "a" and column names which includes "close" with "b":

Namely I want to obtain the below data frame:

  a b
1 1 2
2 4 8
3 5 3

I have a lot of such data frames. The pre values(here it is "df.") are changing but "open" and "close" are fix.

Thanks a lot.

like image 896
oercim Avatar asked Jun 02 '21 17:06

oercim


People also ask

How do I change a column name in R?

To rename a column in R you can use the rename() function from dplyr. For example, if you want to rename the column “A” to “B”, again, you can run the following code: rename(dataframe, B = A) .

How do I change multiple column names in R?

rename() is the method available in the dplyr library which is used to change the multiple columns (column names) by name in the dataframe. The operator – %>% is used to load the renamed column names to the dataframe. At a time it will change single or multiple column names.

How do I convert column values to column names in R?

To convert a column values to column names, we can use dcast function of reshape2 package. For example, if we have a data frame called df that contains two columns say x and y, where x is categorical and y is numerical. Now if we want to convert the categories in x as column names then it can be done as dcast(df,y~x).


Video Answer


1 Answers

We can create a function for reuse

f1 <- function(dat) {
     names(dat)[grep('open$', names(dat))] <- 'a'
      names(dat)[grep('close$', names(dat))] <- 'b'
     dat
}

and apply on the data

df <- f1(df)

-output

df
  a b
1 1 2
2 4 8
3 5 3

if these datasets are in a list

lst1 <- list(df, df)
lst1 <- lapply(lst1, f1)
like image 90
akrun Avatar answered Oct 14 '22 20:10

akrun