Home > OS >  How do I add row values to colnames in R
How do I add row values to colnames in R

Time:12-07

I have a dataframe and I would like to add the first row to the names of the columns

What I have:

col1 col2 col3
city state country
... ... ...

What I want:

col1_city col2_state col3_country
city state country
... ... ...

I can't do it manually because there are many cols in the df

I think of something like

df %>% rename_with(~ names(.) %>% 
                map_chr(~glue('{.x}_.[1,])))

Thanks!!

CodePudding user response:

With rename_with

df %>%
  rename_with(.cols = everything(),
              .fn   = ~paste0(colnames(df), '_', df[1,]))

CodePudding user response:

In base R, just do

names(df) <- paste0(names(df), "_", unlist(df[1,]))

-output

> df
  col1_city col2_state col3_country
1      city      state      country

Or with dplyr

library(dplyr)
library(stringr)
df %>% 
   set_names(str_c(names(.), '_', slice(., 1)))

-output

  col1_city col2_state col3_country
1      city      state      country

data

df <- structure(list(col1 = "city", col2 = "state", 
col3 = "country"), class = "data.frame", row.names = c(NA, 
-1L))

CodePudding user response:

Method 1 : Using paste() method In order to modify the column names, the paste function in R can be used. The paste() method, can be used for the concatenation of string vectors together to form a larger string or sentence. The string vector arguments are joined using the separator specified in the paste function. The changes have to be saved to the original string and are not retained on their own. The strings are concatenated in the order of specification in the method. The method is applied successively to each string in case we specify it over an R list object.

  •  Tags:  
  • r
  • Related