Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

r - 如何重命名data.frame中的单个列?(How to rename a single column in a data.frame?)

I know if I have a data frame with more than 1 column, I can use

(我知道如果我有一个多于一列的数据框,我可以使用)

colnames(x) <- c("col1","col2")

to rename the columns.

(重命名列。)

How do I do this if it's just one column?

(如果只有一栏,该怎么办?)

Meaning a vector or data frame with only one column in it.

(表示其中仅包含一列的向量或数据帧。)

Example:

(例:)

trSamp <- data.frame(sample(trainer$index, 10000))
head(trSamp )
#   sample.trainer.index..10000.
# 1                      5907862
# 2                      2181266
# 3                      7368504
# 4                      1949790
# 5                      3475174
# 6                      6062879

ncol(trSamp)
# [1] 1
class(trSamp)
# [1] "data.frame"
class(trSamp[1])
# [1] "data.frame"
class(trSamp[,1])
# [1] "numeric"
colnames(trSamp)[2] <- "newname2"
# Error in names(x) <- value : 
#   'names' attribute [2] must be the same length as the vector [1]
  ask by screechOwl translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a generalized way in which you do not have to remember the exact location of the variable:

(这是一种通用的方式,您不必记住变量的确切位置:)

# df = dataframe
# old.var.name = The name you don't like anymore
# new.var.name = The name you want to get

names(df)[names(df) == 'old.var.name'] <- 'new.var.name'

This code pretty much does the following:

(此代码几乎可以执行以下操作:)

  1. names(df) looks into all the names in the df

    (names(df)的外观到在所有的名字df)

  2. [names(df) == old.var.name] extracts the variable name you want to check

    ([names(df) == old.var.name]提取您要检查的变量名)

  3. <- 'new.var.name' assigns the new variable name.

    (<- 'new.var.name'分配新的变量名称。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...