简体   繁体   English

如何在循环内更改 R 中的某个列名

[英]How to change a certain columnname in R within a loop

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名称错误("data", i)[5] <- assign(paste0("nfk"), substr(data_files[i], : 分配目标扩展为非语言 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 !我想要做的是用 string(nfk) 重命名第 5 列并将其与列表中的 substr 连接起来(看起来像这样(“_04_05”)。最后 col 5 应该有一个名字像“nfk_04_05”等等我已经尝试了几件事,但到目前为止没有任何工作......你有线索吗?提前非常感谢!

BR BR

Wollbrecht沃尔布莱希特

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?否则下面是猜测,是否有任何原因names(data)[5] <- (paste0("nfk_",substr(data_files[i],1,3)))不会为您解决问题?

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM