Add Empty Columns to a Dataframe with Specified Names from a Vector

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

The problem with your code is in the line:

for(i in length(namevector))

You need to ask yourself: what is length(namevector)? It's one number. So essentially you're saying:

for(i in 11)
df[,i] <- NA

Or more simply:

df[,11] <- NA

That's why you're getting an error. What you want is:

for(i in namevector)
df[,i] <- NA

Or more simply:

df[,namevector] <- NA

Create empty data frame with column names by assigning a string vector?

How about:

df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x

To do all these operations in one-liner:

setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))

#[1] name age gender
#<0 rows> (or 0-length row.names)

Or

data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))

How to add multiple empty columns to an empty data frame?

You can run a for loop

library(tidyverse)

new_col_names <- c("A", "B", "C")

empty_df <- data.frame(col1 = as.Date(character()),
col2 = integer(),
col3 = double())



for (names in new_col_names){
empty_df[,names] <- double()
}

empty_df
#> [1] col1 col2 col3 A B C
#> <0 rows> (or 0-length row.names)

Created on 2021-02-05 by the reprex package (v0.3.0)

Insert a blank column in dataframe

You can add your blank column, re-order, and sort using the code below:

df$blankVar <- NA #blank column 
df[c("Card", "blankVar", "Model_Avg_Error", "Forecast", "Delta")] #re-ordering columns by name
df[order(df$Model_Avg_Error),] #sorting by Model_Avg_Error

Add a vector of strings as new columns in a data.frame?

You can try

df[vec] <- NA

where df is iris in your specific example in the post

Add empty columns to obtain certain amount of columns to existing dataframe

We may use setdiff on the names of the dataset and assign those to NA

df1[setdiff(paste0("F", 1:30), names(df1))] <- NA

-output

> df1
F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 F13 F14 F15 F16 F17 F18 F19 F20 F21 F22 F23 F24 F25 F26 F27 F28 F29 F30
1 1 2 1 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
2 5 5 <NA> NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
3 NA a o NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
4 9 <NA> <NA> NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

Use a vector to create empty columns in a data frame

Since your exampleVector is numeric, you should convert it to
characters when you enter it into the code. Otherwise it will be
interpreted as a selection based on indexes.

exampleVector <- 1:6
exampleDF <- data.frame(First=1:4, Second=4:7,Third=7:10)


exampleDF[as.character(exampleVector)] <- NA_character_

Note that there's no restriction in this setup that protects you
against getting a data frame with the same name occurring several
times. That might create problems later on (if you want to subset
your data frame by names), so I would have added a sanity check to
ensure that you do get unique names.

Is there a way to add only a name to an r data.frame?

In the for cycle, use square brackets [] instead of the dollar sign $

subjects <- unique(exam_results$subject)
column_names <- paste0("subject_", subjects)

for(i in column_names)
exam_results_new_columns[,i] <- NA

Output

#     subject final_score midterm_score subject_maths subject_economics subject_chemistry
# 1 maths 70 53 NA NA NA
# 2 economics 78 66 NA NA NA
# 3 chemistry 61 40 NA NA NA

Create empty tibble/data frame with column names coming from a vector

You can create a named vector, vec, where the first argument sets the type of column you want. The rep("", 3) line says I want three character columns. Then the second argument is the vector of column names.

Use dplyr::bind_rows to convert this into tibble with one row. Then [0, ] selects zero rows, leaving it empty.

With this method, you can control the data type for each column easily.

library(dplyr)

vec <- setNames(rep("", 3), letters[1:3])
bind_rows(vec)[0, ]

# A tibble: 0 x 3
# ... with 3 variables: a <chr>, b <chr>, c <chr>

You can also use as_tibble if you transpose the named vector. I guess I use bind_rows because I usually have dplyr loaded but not tibble.

library(tibble)

vec <- setNames(rep("", 3), letters[1:3])
as_tibble(t(vec))[0, ]

# A tibble: 0 x 3
# ... with 3 variables: a <chr>, b <chr>, c <chr>

If you know all of the columns are of a single type (e.g., character), you can do something like this.

vec <- letters[1:3]
df <- bind_rows(setNames(rep("", length(vec)), vec))[0, ]


Related Topics



Leave a reply



Submit