Home > Software engineering >  how to change column names in sequent in R
how to change column names in sequent in R

Time:11-25

I have summary stats as below (taking from here), and I want to change the name of the columns accordingly. Many thanks in advance.

df <- mtcars
split_data <- split(df, df$cyl)
cols <- lapply(split_data, function(x) psych::describe(x)[c("mean", "sd")]) #["mean"])
df <- do.call(cbind, cols)
df
names(df) <- paste("cyl", names(split_data), sep = ".")
df

Expected answer

       cyl.4.mean  cyl.4.sd  cyl.6.mean  cyl.6.sd   cyl.8.mean  cyl.8.sd  
mpg   26.6636364  4.5098277  19.7428571  1.4535670  15.1000000  2.5600481
cyl    4.0000000  0.0000000   6.0000000  0.0000000   8.0000000  0.0000000
disp 105.1363636 26.8715937 183.3142857 41.5624602 353.1000000 67.7713236
hp    82.6363636 20.9345300 122.2857143 24.2604911 209.2142857 50.9768855
drat   4.0709091  0.3654711   3.5857143  0.4760552   3.2292857  0.3723618
wt     2.2857273  0.5695637   3.1171429  0.3563455   3.9992143  0.7594047
qsec  19.1372727  1.6824452  17.9771429  1.7068657  16.7721429  1.1960138
vs     0.9090909  0.3015113   0.5714286  0.5345225   0.0000000  0.0000000
am     0.7272727  0.4670994   0.4285714  0.5345225   0.1428571  0.3631365
gear   4.0909091  0.5393599   3.8571429  0.6900656   3.2857143  0.7262730
carb   1.5454545  0.5222330   3.4285714  1.8126539   3.5000000  1.5566236

CodePudding user response:

df <- mtcars
split_data <- split(df, df$cyl)
cols <- lapply(split_data, function(x) psych::describe(x)[c("mean", "sd")]) #["mean"])
df <- do.call(cbind, cols)
df
colnames(df) <- paste("cyl", colnames(df), sep = ".")
df

CodePudding user response:

One option is to use rename_with():

library(stringr)
library(dplyr)
df <- mtcars
split_data <- split(df, df$cyl)
cols <- lapply(split_data, function(x) psych::describe(x)[c("mean", "sd")]) #["mean"])
df <- do.call(cbind, cols)

df %>% 
  rename_with(~str_c("cyl.", .), everything())
#>       cyl.4.mean   cyl.4.sd  cyl.6.mean   cyl.6.sd  cyl.8.mean   cyl.8.sd
#> mpg   26.6636364  4.5098277  19.7428571  1.4535670  15.1000000  2.5600481
#> cyl    4.0000000  0.0000000   6.0000000  0.0000000   8.0000000  0.0000000
#> disp 105.1363636 26.8715937 183.3142857 41.5624602 353.1000000 67.7713236
#> hp    82.6363636 20.9345300 122.2857143 24.2604911 209.2142857 50.9768855
#> drat   4.0709091  0.3654711   3.5857143  0.4760552   3.2292857  0.3723618
#> wt     2.2857273  0.5695637   3.1171429  0.3563455   3.9992143  0.7594047
#> qsec  19.1372727  1.6824452  17.9771429  1.7068657  16.7721429  1.1960138
#> vs     0.9090909  0.3015113   0.5714286  0.5345225   0.0000000  0.0000000
#> am     0.7272727  0.4670994   0.4285714  0.5345225   0.1428571  0.3631365
#> gear   4.0909091  0.5393599   3.8571429  0.6900656   3.2857143  0.7262730
#> carb   1.5454545  0.5222330   3.4285714  1.8126539   3.5000000  1.5566236

Created on 2021-11-25 by the reprex package (v2.0.1)

  • Related