79326778

Date: 2025-01-03 14:45:25
Score: 1
Natty:
Report link

I know that this answer doesn't specifically address all of your requirements, but this is the only thread that comes up when I google, "R How do you create a new column in a data.frame for every value in a vector?"

This is a generalized function that creates a data.frame of length len for every value in a vector.

vec_to_col <- function(vec, len) {
  for (i in vec) {
    x <- seq_len(len)
    assign(paste0("ttt", i), x)
  }
  tdf <- data.frame(mget(ls(pattern = "ttt")))
  colnames(tdf) <- gsub("ttt", "", colnames(tdf))
  tdf
}

vec is the vector containing the columns you want to add.

len is the length of the date.frame.

This is a more specific function that creates a data.frame for every value in a vector with a length based on the values of another vector.

vec_to_col <- function(vec1, vec2) {
  for (i in vec1) {
    x <- seq_along(vec2)
    assign(paste0("ttt", i), x)
  }
  tdf <- data.frame(vec2, mget(ls(pattern = "ttt")))
  colnames(tdf) <- gsub("ttt", "", colnames(tdf))
  tdf
}

vec1 is the vector containing the columns you want to add.

vec2 is the vector that has the values you want to be the first column.

Reasons:
  • Blacklisted phrase (1): How do you
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: QQQ-17