How to change a certain columnname in R within a loop

Viewed 22

I have a Code like this

for(i in 1:length(data_files)) {
 assign(paste0(“t”,i),substr(data_files[i],9,14))
 assign(paste0(“data”, i),read.csv2(paste0(“D:/Radar/Duerre/Files/NFK/”,data_files[i])))
 names(“data”,i)[5] <- (paste0("nfk"),substr(data_files[i],9,14))
}

Error in names("data", i)[5] <- assign(paste0("nfk"), substr(data_files[i], : target of assignment expands to non-language object

What I want to do, is to rename the 5th column with string(nfk) and concatenate this with a substr out of a list(whis is looking sth like this ("_04_05") . In the end the col 5 should have a name like "nfk_04_05" and so on I have tried several things but nothing has worked so far…. Do you have a clue ? Many thanks in advance !

BR

Wollbrecht

1 Answers

could you add some sample data? Little tricky to know what you mean without more detail.

Otherwise below is guess, is there any reason names(data)[5] <- (paste0("nfk_",substr(data_files[i],1,3))) won't do the trick for you?

I think I got what you're looking for here:

#generate sample vector and dataframe to try and match your equestion
data_files = c(
  "abcd_1234",
  "efg_567"
)

data = data.frame(
  one = NA,
  two = NA,
  three = NA,
  four = NA,
  five = NA
)

#test a similar loop
for(i in 1:length(data_files)) {
  cat("\n",names(data)) #print column names for validation
  names(data)[5] <- (paste0("nfk_",substr(data_files[i],1,3))) #rename
  cat("\n",names(data)) #recheck
}
Related