In your data.frame
or tibble
you have a column which is a matrix. When showing the data.frame
, it will add .1
, .2
, ... to the column name for each column of the matrix. In a tibble
it will add [,1]
. To be able to rename those columns you can convert the matrix to single columns of the data frame by converting it to a list
and back to a data.frame
.
DF <- data.frame(a = 1:3, b = letters[1:3])
DF$c <- matrix(1:6, 3)
DF
# a b c.1 c.2
#1 1 a 1 4
#2 2 b 2 5
#3 3 c 3 6
as_tibble(DF)
## A tibble: 3 × 3
# a b c[,1] [,2]
# <int> <chr> <int> <int>
#1 1 a 1 4
#2 2 b 2 5
#3 3 c 3 6
names(DF)
#[1] "a" "b" "c"
x <- as.data.frame(as.list(DF))
x
# a b c.1 c.2
#1 1 a 1 4
#2 2 b 2 5
#3 3 c 3 6
names(x)
#[1] "a" "b" "c.1" "c.2"
as.tibble(x)
## A tibble: 3 × 4
# a b c.1 c.2
# <int> <chr> <int> <int>
#1 1 a 1 4
#2 2 b 2 5
#3 3 c 3 6
names(as.tibble(x))
#[1] "a" "b" "c.1" "c.2"
NB
library(dplyr)
library(tibble)
DF <- tibble(a = 1:3, b = letters[1:3])
DF$c <- matrix(1:6, 3)
DF %>% mutate(across(where(is.numeric), scale)) #Given is question of @thole
## A tibble: 3 × 3
# a[,1] b c[,1] [,2]
# <dbl> <chr> <dbl> <dbl>
#1 -1 a -1 -1
#2 0 b 0 0
#3 1 c 1 1
DF |> mutate(across(where(is.numeric), \(x) scale(x)[, 1])) #@dufei
## A tibble: 3 × 3
# a b c
# <dbl> <chr> <dbl>
#1 -1 a -1
#2 0 b 0
#3 1 c 1
numeric_cols <- sapply(DF, is.numeric) #@SamR
DF[numeric_cols] <- scale(DF[numeric_cols])
#Error in `[<-`:
#! Can't recycle `scale(DF[numeric_cols])` (size 3) to size 2.
#Run `rlang::last_trace()` to see where the error occurred.
DF
## A tibble: 3 × 3
# a b c[,1] [,2]
# <int> <chr> <int> <int>
#1 1 a 1 4
#2 2 b 2 5
#3 3 c 3 6