R 从数据框的第一行复制值并重命名列

R 从数据框的第一行复制值并重命名列,r,dataframe,R,Dataframe,如何从数据框的第一行复制值,用该值重命名列名,然后删除该行 例如 到 你可以试试: #create a vector of the first row values and replace the column names names(df) <- unlist(df[1,]) #remove the first row df <- df[-1,] 然后,如果您在使用read.table或类似工具时使用了错误的列名,则可能值得一看 根据@Roland的评论,如果上述转换后的dat

如何从数据框的第一行复制值,用该值重命名列名,然后删除该行

例如

你可以试试:

#create a vector of the first row values and replace the column names
names(df) <-  unlist(df[1,])
#remove the first row
df <- df[-1,]
然后,如果您在使用
read.table
或类似工具时使用了错误的列名,则可能值得一看

根据@Roland的评论,如果上述转换后的data.frame由字符类型(非因子)的数字组成,则使用以下命令将其转换为适当的类型:

df[] <- lapply(df, type.convert)
df[]您可以尝试:

#create a vector of the first row values and replace the column names
names(df) <-  unlist(df[1,])
#remove the first row
df <- df[-1,]
然后,如果您在使用
read.table
或类似工具时使用了错误的列名,则可能值得一看

根据@Roland的评论,如果上述转换后的data.frame由字符类型(非因子)的数字组成,则使用以下命令将其转换为适当的类型:

df[] <- lapply(df, type.convert)

df[]你自己已经试过了吗?为什么不起作用?您是如何得到这种格式的数据帧的?最好是在上游而不是下游解决这个问题。我猜这可能是因为在
read.table
中没有指定
header=TRUE
?您自己已经尝试过了吗?为什么不起作用?您是如何得到这种格式的数据帧的?最好是在上游而不是下游解决这个问题。我猜这可能是在
read.table
中没有指定
header=TRUE
的情况。如果这样做,以后应该应用
type.convert
。@Roland这确实是一个很好的补充。但是,我怀疑这不是OP的真实data.frame。如果你这样做,你应该在之后应用
type.convert
。@Roland这确实是一个不错的添加。但我怀疑这不是OP的真实数据帧。
df[] <- lapply(df, type.convert)