Reputation: 143
I would like to create a user-defined function with a for-loop that adds to each column name the number of the column in order to add clarity to my data frame.
Here is the code (but doesn't work):
addncol = function(df)
{
for(i in 1:ncol(df))
{
names(df)[[i]] <- paste(names(df)[[i]], i, sep = '_')
}
}
The for-loop alone works well but in the function it doesn't work (I have no error message though).
Upvotes: 0
Views: 1582
Reputation: 59425
You could use data.tables for this, which updates by reference using setnames(...)
(note the different spelling - it's a different function).
library(data.table)
DT <- as.data.table(mtcars) # example only
head(DT)
mpg cyl disp hp drat wt qsec vs am gear carb
# 1: 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
# 2: 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
# 3: 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
# 4: 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
# 5: 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
# 6: 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
addncol <- function(DT) setnames(DT,paste(names(DT),seq(DT),sep="_"))
addncol(DT)
head(DT)
# mpg_1 cyl_2 disp_3 hp_4 drat_5 wt_6 qsec_7 vs_8 am_9 gear_10 carb_11
# 1: 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
# 2: 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
# 3: 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
# 4: 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
# 5: 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
# 6: 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
Upvotes: 1
Reputation: 81743
The function doesn't return the data frame df
. It will work if you add df
as the last line of your function.
However, a simpler version without loops is a vectorized approach with setNames
:
addncol <- function(df)
setNames(df, paste(names(df), seq(df), sep = "_"))
Upvotes: 2