cbind a dynamic column name from a string in R

后端 未结 4 2172
-上瘾入骨i
-上瘾入骨i 2021-01-19 03:35

I want to cbind a column to the data frame with the column name dynamically assigned from a string

y_attribute = \"Survived\"
cbind(test_data, y_attribute =         


        
相关标签:
4条回答
  • 2021-01-19 04:12

    Not proud of this but I usually will do somethingl like this:

    dyn.col <- "XYZ"
    cbind(test.data, UNIQUE_NAMEXXX=NA)
    colnames(test.data)[colnames(test.data == 'UNIQUE_NAMEXXX')] <- dyn.col
    
    0 讨论(0)
  • 2021-01-19 04:20

    You don't actually need cbind to add a new column. Any of these will work:

    test_data[, y_attribute] = NA # data frame row,column syntax
    test_data[y_attribute] = NA   # list syntax (would work for multiple columns at once)
    test_data[[y_attribute]] = NA # list single item syntax (single column only)
    

    New columns are added after the existing columns, just like cbind.

    0 讨论(0)
  • 2021-01-19 04:25

    We can use tidyverse to do this

    library(dplyr)
    test_data %>%
         mutate(!! y_attribute := NA)
    #   col1 Survived
    #1    1       NA
    #2    2       NA
    #3    3       NA
    #4    4       NA
    #5    5       NA
    

    data

    test_data <- data.frame(col1 = 1:5)
    
    0 讨论(0)
  • 2021-01-19 04:31

    We can also do it with data.table

    library(data.table)
    setDT(test_data)[, (y_attribute) := NA]
    
    0 讨论(0)
提交回复
热议问题