重命名数据框中的列

Renaming columns in a data frame

我有以下数据框:

structure(list(D1 = structure(list(t.t.scale.x.....sd...mean. = c(95.0871563564004, 88.072473285318, 116.840370358282)), class = "data.frame", row.names = c(NA, -3L)), D2 = structure(list(t.t.scale.x.....sd...mean. = c(96.7679763688573, 116.352548635184, 86.8794749959586)), class = "data.frame", row.names = c(NA, -3L)), D3 = structure(list(t.t.scale.x.....sd...mean. = c(92.420897699915, 90.3018565270302, 117.277245773055)), class = "data.frame", row.names = c(NA, -3L)), D4 = structure(list(t.t.scale.x.....sd...mean. = c(96.6694428192656, 86.945205844304, 116.38535133643)), class = "data.frame", row.names = c(NA, -3L)), D5 = structure(list(t.t.scale.x.....sd...mean. = c(82.8720020998492, 106.333804799486, 110.794193100665)), class = "data.frame", row.names = c(NA, -3L))), class = "data.frame", row.names = c("GG", "GV", "AR"))

我正在尝试使用以下方法重命名列:

colnames(x) <- c("a", "b","c","d","e") 

但是名字根本没有变。

我可以复制你的发现。可能是因为你的结构有两个或多个结构堆叠。

dat
   t.t.scale.x.....sd...mean. t.t.scale.x.....sd...mean.
GG                   95.08716                   96.76798
GV                   88.07247                  116.35255
AR                  116.84037                   86.87947
   t.t.scale.x.....sd...mean. t.t.scale.x.....sd...mean.
GG                   92.42090                   96.66944
GV                   90.30186                   86.94521
AR                  117.27725                  116.38535
   t.t.scale.x.....sd...mean.
GG                    82.8720
GV                   106.3338
AR                   110.7942

colnames(dat)
[1] "D1" "D2" "D3" "D4" "D5"

您可以通过转换为矩阵然后返回数据框来解决此问题

dat <- data.frame( as.matrix( dat ) )
dat
          D1        D2        D3        D4       D5
GG  95.08716  96.76798  92.42090  96.66944  82.8720
GV  88.07247 116.35255  90.30186  86.94521 106.3338
AR 116.84037  86.87947 117.27725 116.38535 110.7942

colnames(dat) <- c("a","b","c","d","e")
dat
           a         b         c         d        e
GG  95.08716  96.76798  92.42090  96.66944  82.8720
GV  88.07247 116.35255  90.30186  86.94521 106.3338
AR 116.84037  86.87947 117.27725 116.38535 110.7942

正确的结构应该是这样的

dput(dat)
structure(list(D1 = c(95.0871563564004, 88.072473285318, 116.840370358282
), D2 = c(96.7679763688573, 116.352548635184, 86.8794749959586
), D3 = c(92.420897699915, 90.3018565270302, 117.277245773055
), D4 = c(96.6694428192656, 86.945205844304, 116.38535133643), 
    D5 = c(82.8720020998492, 106.333804799486, 110.794193100665
    )), class = "data.frame", row.names = c("GG", "GV", "AR"))