Joel B Joel B - 3 months ago 4
R Question

renaming a column in a dataframe using a value from the global environment in R

I have a data frame (summary_transposed_no_time) and I want to rename one of the columns to a name I have stored as a value.

summary_transposed_no_time looks like this:

| A | B | C | D
------ | ------ | ------ | ------ | ------
area_1 | 0.870 | 0.435 | 0.968 | 0.679
area_2 | 0.456 | 0.259 | 0.906 | 0.467
area_3 | 0.298 | 0.256 | 0.457 | 0.768
area_4 | 0.994 | 0.987 | 0.365 | 0.765


My value is called test and it is set to "B" so I have tried using the following code with no luck:

summary_transposed_no_time <- names(summary_transposed_no_time)[c(test_col)]<-c("test")


Desire output

| A | test | C | D
------ | ------ | ------ | ------ | ------
area_1 | 0.870 | 0.435 | 0.968 | 0.679
area_2 | 0.456 | 0.259 | 0.906 | 0.467
area_3 | 0.298 | 0.256 | 0.457 | 0.768
area_4 | 0.994 | 0.987 | 0.365 | 0.765

Answer

I think you need (I have replaced summary_transposed_no_time with x)

names(x)[match(test_col, names(x))] <- "test"

x <- trees[1:5, ]
#  Girth Height Volume
#1   8.3     70   10.3
#2   8.6     65   10.3
#3   8.8     63   10.2
#4  10.5     72   16.4
#5  10.7     81   18.8

names(x)[match("Girth", names(x))] <- "test"
#   test Height Volume
#1  8.3     70   10.3
#2  8.6     65   10.3
#3  8.8     63   10.2
#4 10.5     72   16.4
#5 10.7     81   18.8
Comments