当我创建数据帧时,我有一组43个变量/列默认命名为X1,X2,X3 ..... X46。我需要用Q来重温X.有更快的方法在R中执行此操作,还是必须在每个X上单独使用rename()?请帮助,我想学习有效的方法来实现这一目标! (我是新手R程序员)
答案 0 :(得分:5)
names(dataframe) <- gsub("X", "Q", names(dataframe), fixed = TRUE)
fixed = TRUE
使得它更快,因为您没有使用实际的正则表达式。
答案 1 :(得分:2)
假设cols
是列名称的向量,您可以使用gsub
替换。
> cols
## [1] "X1" "X2" "X3" "X4" "X5" "X6" "X7" "X8" "X9" "X10" "X11" "X12" "X13" "X14"
##[15] "X15" "X16" "X17" "X18" "X19" "X20" "X21" "X22" "X23" "X24" "X25" "X26" "X27" "X28"
##[29] "X29" "X30" "X31" "X32" "X33" "X34" "X35" "X36" "X37" "X38" "X39" "X40" "X41" "X42"
##[43] "X43"
> gsub("X", "Q", cols)
## [1] "Q1" "Q2" "Q3" "Q4" "Q5" "Q6" "Q7" "Q8" "Q9" "Q10" "Q11" "Q12" "Q13" "Q14"
##[15] "Q15" "Q16" "Q17" "Q18" "Q19" "Q20" "Q21" "Q22" "Q23" "Q24" "Q25" "Q26" "Q27" "Q28"
##[29] "Q29" "Q30" "Q31" "Q32" "Q33" "Q34" "Q35" "Q36" "Q37" "Q38" "Q39" "Q40" "Q41" "Q42"
##[43] "Q43"
答案 2 :(得分:0)
假设df
是您的数据框,例如
> df = data.frame(matrix(0,1,43))
您可以先清空当前列名,然后使用任何所需的前缀命名它们,例如: "Q"
,使用:
> colnames(df)=NULL
> colnames(df)=colnames(df, do.NULL=FALSE, prefix="Q")