s_baldur
s_baldur

Reputation: 33488

Get new data.frame column name in cbind from a character

I'm trying to assign a 'data.frame column name' from a character that is automatically generated by R in a function. I know I could update column names afterwards with colnames() but feel I should know how to do it directly.

Example:

test <- iris[1:3, 1:2]
i <- 3
hat_char <- paste0("hat", i) 
x <- cbind(test, hat_char = 3:1)
x
  Sepal.Length Sepal.Width hat_char
1          5.1         3.5        3
2          4.9         3.0        2
3          4.7         3.2        1

Hoped-for output

  Sepal.Length Sepal.Width hat3
1          5.1         3.5    3
2          4.9         3.0    2
3          4.7         3.2    1

This seems hard to search for due to an avalanche of related but different and more basic questions.

EDIT: Forgot to mention but would strongly prefer base R solutions.

Upvotes: 2

Views: 1179

Answers (1)

akrun
akrun

Reputation: 887148

Using setNames from base R

cbind(test, setNames(list(3:1), hat_char))
#    Sepal.Length Sepal.Width hat3
#1          5.1         3.5    3
#2          4.9         3.0    2
#3          4.7         3.2    1

If we assign it to the same dataset

test[hat_char] <- 3:1

If we are using dplyr

library(dplyr)
test %>%
  mutate(!! hat_char := 3:1)
#    Sepal.Length Sepal.Width hat3
#1          5.1         3.5    3
#2          4.9         3.0    2
#3          4.7         3.2    1

Upvotes: 2

Related Questions