重命名列而不会丢失值R.

时间:2018-03-26 13:26:48

标签: r

我有一个数据集,其中列名实际上是数据点。我无法使用read函数中的可用修改,因为数据已加载到会话中。如果我重命名该列,我将丢失第一行中的值,这是不可接受的。如何将这些值向下移动并添加标题?

# Data looks like this
blue <- c('yellow', 'red', 'green')
primary <- c('primary', 'primary', 'secondary')
have <- data.frame(blue, primary)

# I can rename columns but I'll lose that row of data
colnames(have) <- c('color', 'type')

# This is what I want
color <- c('blue', 'yellow', 'red', 'green')
type <- c('primary', 'primary', 'primary', 'secondary')
want <- data.frame(color, type)

2 个答案:

答案 0 :(得分:1)

这是一种方式。
首先,在更改名称之前输入数据。

blue <- c('yellow', 'red', 'green')
primary <- c('primary', 'primary', 'secondary')
have <- data.frame(blue, primary)

现在代码。

want2 <- have
want2[] <- lapply(have, as.character)
want2 <- rbind(names(want2), want2)
names(want2) <- c('color', 'type')
want2
#   color      type
#1   blue   primary
#2 yellow   primary
#3    red   primary
#4  green secondary

答案 1 :(得分:0)

您必须将数据框标题复制到新行:

have[,1] = factor(have[,1],levels = c("blue","yellow","red","green")) #This is to define that "blue" is a factor
have[4,] = colnames(have) # Adds the table header to line 4
colnames(have) <- c('color', 'type') # redefine header