I have this data set (supposing it is big with many rows and columns)
df = data.frame(x = c(1,2,3,4),
y = c(2,4,5,6) )
and I want it to become like this using the names of variables x, y, etc ... with a simple function
df = data.frame(x = c('x_1','x_2','x_3','x_4'),
y = c('y_2','y_4','y_5','y_6') )
appreciate the help
CodePudding user response:
mapply(paste, colnames(df), df, sep = "_")
CodePudding user response:
library(purrr)
imap_dfr(df, ~ paste0(.y, '_', .x))
CodePudding user response:
You can use sapply
which will go through every column and apply the paste
function:
sapply(colnames(df), function(var) paste(var, df[,var], sep="_"))
x y
[1,] "x_1" "y_2"
[2,] "x_2" "y_4"
[3,] "x_3" "y_5"
[4,] "x_4" "y_6"
sapply
returns a matrix, so you can add as.data.frame
if that is the format you want.
as.data.frame(sapply(colnames(df), function(var) paste(var, df[,var], sep="_")))
x y
1 x_1 y_2
2 x_2 y_4
3 x_3 y_5
4 x_4 y_6