user7649990
user7649990

Reputation:

New column in the data.frame not getting the name assigned to it in R

I'm trying to scale my data and add it to my original data with a new name. I was wondering though why my scaled data does not get the new name assigned to it?

Here is what I tried:

    data <- mtcars["wt"]
    d <- scale(data)
    data[, paste0(names(data), ".bbb") ] <- d
    data
                    wt           wt   ## HERE 2nd column name has not changed I expect it to be "wt.bbb"
Mazda RX4        2.620   -0.610399567
Mazda RX4 Wag    2.875   -0.349785269

Upvotes: 1

Views: 53

Answers (4)

Benjamin Christoffersen
Benjamin Christoffersen

Reputation: 4841

I was wondering though why my scaled data does not get the new name assigned to it?

It is because

class(d)
#R> [1] "matrix"
colnames(d)
#R> [1] "wt"

Thus, you could do

data <- mtcars["wt"]
data[paste0(names(data), ".bbb")] <- unname(scale(data))
data
#R>                       wt   wt.bbb
#R>Mazda RX4           2.620 -0.61040
#R>Mazda RX4 Wag       2.875 -0.34979
#R>Datsun 710          2.320 -0.91700
#R>Hornet 4 Drive      3.215 -0.00230
#C> [output abbreviated]

See help("print.data.frame") and call format with a matrix which has column names.

Upvotes: 0

Julius Vainora
Julius Vainora

Reputation: 48201

Because d is a matrix with a column already having a name, and it happens that this name wins. Few minimal changes to your approach to fix that would be:

data[, paste0(names(data), ".bbb") ] <- d[, 1]
data[, paste0(names(data), ".bbb") ] <- as.numeric(d)
data[, paste0(names(data), ".bbb") ] <- as.vector(d)
data[, paste0(names(data), ".bbb") ] <- c(d)

Upvotes: 2

Jordi
Jordi

Reputation: 1343

Why not just do

df <- mtcars
df$wt.bbb <- scale(df$wt)

Upvotes: 1

Andrew Patton
Andrew Patton

Reputation: 1

Go take a look at ?scale() - you'll see that what you return is not just a vector of numbers, but actually a matrix. Therefore, you'll need a little more noodling to get what you want.

data <- mtcars["wt"]
scaled_matrix <- scale(data)
class(scaled_matrix)
scaled_values <- scaled_matrix[1:32]
class(scaled_values)

dplyr version

data %>% 
  mutate(your_name_here = d)

non-dplyr version

df <- cbind(data, "your_name_here" = scaled_values)

Upvotes: 0

Related Questions