user8419142
user8419142

Reputation: 27

Concatenate column name and 1st row in R

I have a data frame with 3 columns

data.frame(A=c(1, 2, 3), B=c('a', 'b', 'c'), C=c(22, 21, 22))

I would like to combine the first row with column name as the final column name So column A would be named "A_1" and would have values (a,22) and so on... Can anyone help me?

[EDIT - ANSWER] I managed this with the following:

columns = paste(names(df),as.matrix(df[1,]))
columns %>% str_remove(' NA') # to remove the "NA"'s I had in 1st row
colnames(df) = columns

Snap of dataset

pseudospin output

Upvotes: 3

Views: 2298

Answers (2)

rodolfoksveiga
rodolfoksveiga

Reputation: 1261

I think this may solve your problem:

library(dplyr)
library(stringr)

df = data.frame('A' = c(NA, 1, 2),
                'B' = c('%', 6.49, 6.42),
                'C' = c('mg/l', 5.7, 8.4))
cols = df %>%
  colnames() %>%
  paste(df[1, ], sep = '_') %>%
  str_remove('_NA')

df %>%
  'colnames<-'(cols) %>%
  slice(-1) %>%
  apply(2, as.numeric) %>%
  as.data.frame()

Here is the output:

  A  B_% C_mg/l
1 1 6.49    5.7
2 2 6.42    8.4

Note that it was important to remove the NA values from the column names in order to keep it clean.

Upvotes: 1

pseudospin
pseudospin

Reputation: 2767

Possibly some confusion with rows and columns? Is this what you mean?

df <- data.frame(A=c(1, 2, 3), B=c('a', 'b', 'c'), C=c(22, 21, 22))
colnames(df) <- paste(sep = '_', colnames(df), as.character(unlist(df[1,])))
df <- df[-1, ]
df
#>   A_1 B_a C_22
#> 2   2   b   21
#> 3   3   c   22

Upvotes: 5

Related Questions