Add empty columns to a dataframe with specified names from a vector

前端 未结 4 1606
执念已碎
执念已碎 2020-11-30 02:36

I have a dataframe, df, with a a number of columns of data already. I have a vector, namevector, full of strings. I need empty columns added to

4条回答
  •  忘掉有多难
    2020-11-30 02:47

    set.seed(1)
    example <- data.frame(col1 = rnorm(10, 0, 1), col2 = rnorm(10, 2, 3))
    namevector <- c("col3", "col4")
    example[ , namevector] <- NA
    
    example
    #          col1       col2 col3 col4
    # 1  -0.6264538  6.5353435   NA   NA
    # 2   0.1836433  3.1695297   NA   NA
    # 3  -0.8356286  0.1362783   NA   NA
    # 4   1.5952808 -4.6440997   NA   NA
    # 5   0.3295078  5.3747928   NA   NA
    # 6  -0.8204684  1.8651992   NA   NA
    # 7   0.4874291  1.9514292   NA   NA
    # 8   0.7383247  4.8315086   NA   NA
    # 9   0.5757814  4.4636636   NA   NA
    # 10 -0.3053884  3.7817040   NA   NA
    

提交回复
热议问题