使用大量列更改数据框的名称的有效方法

时间:2014-11-19 15:53:36

标签: r

存在一个包含80列的数据框,我想将其列名更改为......

t1   t2   t3  t4  t5  t6 ... t80

有没有有效的方法来完成这种任务?谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用效率稍高的paste0

colnames(data) <- paste0("t", 1:80)

# paste0("t", 1:80) will give you:
 [1] "t1"  "t2"  "t3"  "t4"  "t5"  "t6"  "t7"  "t8"  "t9"  "t10" "t11" "t12" "t13" "t14" "t15"
[16] "t16" "t17" "t18" "t19" "t20" "t21" "t22" "t23" "t24" "t25" "t26" "t27" "t28" "t29" "t30"
[31] "t31" "t32" "t33" "t34" "t35" "t36" "t37" "t38" "t39" "t40" "t41" "t42" "t43" "t44" "t45"
[46] "t46" "t47" "t48" "t49" "t50" "t51" "t52" "t53" "t54" "t55" "t56" "t57" "t58" "t59" "t60"
[61] "t61" "t62" "t63" "t64" "t65" "t66" "t67" "t68" "t69" "t70" "t71" "t72" "t73" "t74" "t75"
[76] "t76" "t77" "t78" "t79" "t80"

# If you want padding, you do:
colnames(data) <- sprintf("t%02d", 1:80)

# sprintf("t%02d", 1:80) will give you:
 [1] "t01" "t02" "t03" "t04" "t05" "t06" "t07" "t08" "t09" "t10" "t11" "t12" "t13" "t14" "t15"
[16] "t16" "t17" "t18" "t19" "t20" "t21" "t22" "t23" "t24" "t25" "t26" "t27" "t28" "t29" "t30"
[31] "t31" "t32" "t33" "t34" "t35" "t36" "t37" "t38" "t39" "t40" "t41" "t42" "t43" "t44" "t45"
[46] "t46" "t47" "t48" "t49" "t50" "t51" "t52" "t53" "t54" "t55" "t56" "t57" "t58" "t59" "t60"
[61] "t61" "t62" "t63" "t64" "t65" "t66" "t67" "t68" "t69" "t70" "t71" "t72" "t73" "t74" "t75"
[76] "t76" "t77" "t78" "t79" "t80"