0
votes

I have a vector of names, like so:

sites <- paste("website", 1:10, sep = ".")

Using the names in the vector defined above, I would like to

  1. create 10 vectors/variables, all of length nrow(dataframe).
  2. assign each vector a value of NA.

I understand how to use assign to give the variables specific values, but i can't seem to find a simple answer for how to create the variables themselves. Seems like an easy question but I can't find a straightforward answer.

The desired result is ten variables named dataframe$website.1....dataframe$website.10, with length of nrow(dataframe). Thanks.

1
as.data.frame(matrix(NA, nrow(dataframe), 10, dimnames = list(NULL, paste('website', 1:10, sep = '.')))) perhaps, though this seems the precursor to bad idioms. - alistaire

1 Answers

2
votes

To get a vector of NA, you can do:

na_vector <- rep(NA, nrow(dataframe))

I'm not entirely clear what you're looking for after that, but if you want to add those NA vectors to a dataframe, one option is

for (s in sites) {
  dataframe[[s]] <- na_vector  # to add a column to a data frame
}