user9370546
user9370546

Reputation:

looping through columns and adding iteration number to respective column name

I have a data frame with experimental data. I want to name certain parts of the data frame the following way: "expA_mult4_belA4" and add a suffix "_inv" where inv is a loop iteration from 1 to 10.

for(inv in 1:10){ colnames(data)[18:27] <- paste("expA_mult4_belA4",inv,sep="_") }

The code output is close, but the problem is that the suffix is always 10 for all my variables in columns 18 to 27. I want the suffixes to be for the first variable 1, second 2, ..., tenth 10. Thanks in advance.

Upvotes: 0

Views: 273

Answers (1)

moodymudskipper
moodymudskipper

Reputation: 47300

You don't need the loop:

data <- iris
colnames(data)[2:3] <- paste("test",1:2,sep="_")
head(data)  
#   Sepal.Length test_1 test_2 Petal.Width Species
# 1          5.1    3.5    1.4         0.2  setosa
# 2          4.9    3.0    1.4         0.2  setosa
# 3          4.7    3.2    1.3         0.2  setosa
# 4          4.6    3.1    1.5         0.2  setosa
# 5          5.0    3.6    1.4         0.2  setosa
# 6          5.4    3.9    1.7         0.4  setosa

Upvotes: 1

Related Questions