【问题标题】:extracting or merging columns in a specific order in R在R中以特定顺序提取或合并列
【发布时间】:2017-02-09 15:58:51
【问题描述】:

我有一个包含 300 多个变量的纵向数据框,一个医院数据库。对于某个临床测试,我提取了该测试的测试值和访问日期,这也对应于 dplyr 包的测试日期如下:

df_VL<- select(df, ends_with("vload"))
df_dat<- select(df, ends_with("datvisit"))

然后我merge这两个和cbind

df_x<- cbind(df_VL,df_dat)

但这首先给了我所有的测试结果,然后是测试日期。

我需要 按时间顺序逐一提取以"vload""datvisit"结尾的所有变量,例如-->“t0datvisit”、“t0vload”、“t6datvisit”、“t6vload”、.......“t180datvisit ", "t180vload" 或者 按此顺序再次合并两个数据帧的列 --> "t0datvisit", "t0vload","t6datvisit", "t6vload",......."t180datvisit", "t180vload"

你知道怎么做吗?

【问题讨论】:

    标签: r merge extraction


    【解决方案1】:

    考虑 mapply 映射两个数据框名称,然后转换为字符向量以获得新的列名称顺序:

    df_x <- cbind(df_VL, df_dat)
    
    ord_names <- as.vector(mapply(c, names(df_VL), names(df_dat)))
    
    df_x <- df_x[ord_names]
    

    【讨论】:

    • 有效!谢谢!为了更好地理解语法:“c”,它是什么意思?对不起,如果这是个愚蠢的问题,我是初学者。
    • 太棒了!如果回答有帮助,请接受它(在旁边打勾)以确认解决方案。 c 指的是 c() 基本 R 函数,它将值组合到向量或列表中。
    【解决方案2】:

    我认为这可行

    colnames( mtcars )[1:6]

    # get all the numbers out of the colnames   
    matches <- regmatches(colnames(mtcars), gregexpr("[[:digit:]]+",  colnames( mtcars)))
    a<-unique( as.numeric(unlist(matches)) )
    #order them numerically
    a <- sort(a )
    
    # create an object with the ars ordered numerically
    f <- NULL 
    for( b in a){ 
    f <- c( f ,  paste0("t" , b, "datvisit") ,  paste0("t" , b, "vload")  )
    }
    
    # just those vars 
    head( mtcars[ , f ] )
    
    # or those vars and the other cols
    others <- colnames( mtcars )[ !(colnames(mtcars) %in% f) ]
    head( mtcars[ ,c( others, f)  ] )
    

    如果你想做所有的“datvisits”,而不是“vloads”它更容易

    head( mtcars[ , c( 
                grep(  "datvisit" , colnames( mtcars) ) ,
                grep(  "vload" , colnames( mtcars) )
                )])
    

    【讨论】:

    • 谢谢,但它给出了一个错误:选择了未定义的列,我已经有了像你的第二个建议一样的 df_x,但我希望测试结果和它的日期并排。
    • @trillian 您需要将 mtcars 替换为您的数据集的名称:我刚刚运行了这一行 colnames( mtcars )[1:6]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多