按位置重命名R中的一组列 [英] Rename a set of columns in R by position
问题描述
我有一个数据框,我想在其中重命名45列中的30列。这30列具有不同的名称(它们来自不同的来源),但是它们始终位于数据框中的位置2:31。有没有一种方法可以按照 names(df)[2:31]<-c( name1, name2,..., name30 )
?另外,有没有一种方法可以使用dplyr的 rename
命令而不给出列的名称,而是给出它们的位置?
<我知道这是一种基本的方法,但是我能找到的所有解决方案都需要相反的方法,在未知位置重命名具有已知名称的列。
使用 colnames()
函数
X<-data.frame(坏= 1:3,更糟= 1:3)
姓(X)[1:2 ]<-c( name1, name2)
您可以使用 colnames()
,然后子集传递带有名称的数组。希望对您有所帮助。
I have a data frame where I want to rename 30 out 45 columns. These 30 columns have different names (they come from different sources), but they are always in position 2:31 in the dataframe. Is there a way to rename columns 2:31 something along the lines of names(df)[2:31]<- c("name1", "name2", ..., "name30")
? Alternatively, is there a way to use dplyr's rename
command without giving the names of the columns and instead give their positions?
I know this is sort of basic, but all solutions I could find wanted the opposite, rename a column with a known name at an unknown position.
Use the colnames()
function
X <- data.frame(bad=1:3, worse=1:3)
colnames(X)[1:2] <- c("name1", "name2")
You can use colnames()
and then subset and pass an array with the names. Hope it helps.
这篇关于按位置重命名R中的一组列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!