-1

我有一组数据框,我正在努力更改其上的列名

for(i in c("ML","HL","MSMS","PEP","MqNormHM","MixHM","RawHM","AbsHM","SepAbsHM")){
  j<-ifelse(i %in% c("ML","HL","MSMS","PEP","MqNormHM"),paste("Rel",i,sep=""),i)
  colnames(get(j))<-paste(i,colnames(get(j)),sep="")
}

给我:

Error in colnames(get(j)) <- paste(i, colnames(get(j)), sep = "") : 
  could not find function "get<-"

ML、HL 等是以下形式的单个数据帧:

> head(RelML)
          AA       BB       CC       DD       EE      LL      MM      NN
2684 0.19650       NA       NA       NA       NA      NA      NA      NA
4470      NA       NA       NA       NA       NA 0.35249      NA 0.35797
3619 0.22108 0.098167 0.041080       NA       NA      NA      NA      NA
5422      NA       NA 0.052223       NA       NA      NA      NA      NA
1286      NA       NA       NA       NA 0.019568      NA 0.31137 0.34364
1918      NA       NA       NA 0.026735       NA      NA      NA      NA

并且在所有情况下,数据框的名称都开始为,例如:

> colnames(RelML)
[1] "AA" "BB" "CC" "DD" "EE" "LL" "MM" "NN"

我希望它最终成为 RelML 数据框的情况:

> paste("ML",colnames(RelML),sep="")
[1] "MLAA" "MLBB" "MLCC" "MLDD" "MLEE" "MLLL" "MLMM" "MLNN"

我尝试过使用 get(colnames(j))、colnames(as.name(j)) 等等,但似乎没有任何效果。任何帮助将不胜感激。问候马德斯

4

2 回答 2

1

您不能get一次性反对和修改其列。您需要将其分解为多个语句以获取、修改和重新分配:

for (i in c("ML","HL","MSMS","PEP","MqNormHM",
            "MixHM","RawHM","AbsHM","SepAbsHM")) {
  j <- ifelse(i %in% c("ML","HL","MSMS","PEP","MqNormHM"),
              paste("Rel", i, sep = ""), i)
  o <- get(j)
  colnames(o) <- paste(i, colnames(o), sep = "")
  assign(j, o, envir = .GlobalEnv)
}

您可以通过执行以下操作使所有这些矢量化并更简洁:

z  <- c("ML","HL","MSMS","PEP","MqNormHM")
i  <- c("ML","HL","MSMS","PEP","MqNormHM","MixHM","RawHM","AbsHM","SepAbsHM")
j  <- ifelse(i %in% z, paste0("Rel", i), i)
o1 <- mget(j, envir = .GlobalEnv)
n1 <- lapply(o1, colnames)
n2 <- Map(paste0, i, n1)
o2 <- Map(`colnames<-`, o1, n2)

invisible(list2env(o2, .GlobalEnv))

现在通常的免责声明:必须依赖get/mget并且assign通常是不良做法的标志。您应该将它们存储到一个列表中,然后使用lapply(和其他)一起处理它们,而不是在您的环境中拥有很多相似的对象。

于 2013-11-01T17:06:18.170 回答
0

我想你正在努力做到这一点 -

library(data.table)
for(i in c("ML","HL","MSMS","PEP","MqNormHM","MixHM","RawHM","AbsHM","SepAbsHM"))
      {
        j<-ifelse(i %in% c("ML","HL","MSMS","PEP","MqNormHM"),paste("Rel",i,sep=""),i)
        setnames(get(j), paste(i,colnames(get(j)),sep=""))
    }

不同之处仅在于我使用data.table::setnames.

于 2013-11-01T17:03:42.930 回答