gpt4 book ai didi

r - 在 R 中,如何将列名打印成向量形式?

转载 作者:行者123 更新时间:2023-12-05 01:11:22 28 4
gpt4 key购买 nike

我有一个包含数百列的数据框。我需要采用多组列来应用转换。必须复制粘贴,然后插入逗号并删除多余的空间非常耗时。这里以一个只有 13 列的数据框为例。

df <- data.frame(x1=rnorm(20),x2=rnorm(20),x3=rnorm(20)
,x4=rnorm(20),x5=rnorm(20),x6=rnorm(20),x7=rnorm(20)
,x8=rnorm(20),x9=rnorm(20),x10=rnorm(20),x11=rnorm(20)
,x12=rnorm(20),x13=c(2,1,1,2,2,1,2,1,2,2,1,1,2,1,2,2,1,2,1,1))

我可以打印名称,但它们看起来像:

colnames(df)
[1] "x1" "x2" "x3" "x4" "x5" "x6" "x7" "x8" "x9" "x10" "x11" "x12" "x13"

我想要

c("x1","x2","x3","x4","x5","x6","x7","x8","x9","x10","x11","x12","x13")

我尝试过的:

paste0("c(",paste(names(df),collapse=","),")")
[1] "c(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13)"

paste0("c(",paste(names(df),collapse="\",\""),")")
[1] "c(x1\",\"x2\",\"x3\",\"x4\",\"x5\",\"x6\",\"x7\",\"x8\",\"x9\",\"x10\",\"x11\",\"x12\",\"x13)"

paste0("c(",paste(names(df),collapse="','"),")")
[1] "c(x1','x2','x3','x4','x5','x6','x7','x8','x9','x10','x11','x12','x13)"

paste0("c(",paste(str(names(df)),collapse=","),")")
chr [1:13] "x1" "x2" "x3" "x4" "x5" "x6" "x7" "x8" "x9" "x10" "x11" "x12" "x13"
[1] "c()"

最佳答案

使用dput()函数

    df <- data.frame(x1=rnorm(20),x2=rnorm(20),x3=rnorm(20)
,x4=rnorm(20),x5=rnorm(20),x6=rnorm(20),x7=rnorm(20)
,x8=rnorm(20),x9=rnorm(20),x10=rnorm(20),x11=rnorm(20)
,x12=rnorm(20),x13=c(2,1,1,2,2,1,2,1,2,2,1,1,2,1,2,2,1,2,1,1))

x <- colnames(df)

dput(x)
#> c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10",
#> "x11", "x12", "x13")

reprex package 创建于 2020-08-11 (v0.3.0)

关于r - 在 R 中,如何将列名打印成向量形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63361833/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com