0

Suppose I have a vector of character strings that I'd like to use to name new columns in a data.frame. I could do this:

my_strings = c("Some", "Strings", "Here")
for (i in my_strings) {
  df[,i] = 1
}

And get three new columns in the df name appropriately. But if instead I did

my_strings = c("Some", "Strings", "Here")
for (i in my_strings) {
  df$i = 1
}

I'll just get one new column named "i". This isn't a problem with data frames but some objects are difficult or impossible to modify without using the $ operator - is there some way to feed it a variable to interpret as a character?

Slavatron
  • 2,278
  • 5
  • 29
  • 40
  • Can you give an example of this non-data frame in which the dollar sign access of columns is an issue? This sounds like a data type-specific issue and it is difficult to give an accurate answer without knowing what that data type is. Otherwise, I don't think it's possible to use the dollar sign like you want. – Eric Leung Aug 01 '17 at 21:53
  • No, it's not. You can always use `[[`, i.e., `your_object[[i]] = 1`. See `fortunes::fortune(312)`, `fortunes::fortune(343)`, and the dupe. (Happy to re-open if you can provide an example where `$` works but `[[` doesn't.) – Gregor Thomas Aug 01 '17 at 21:54

0 Answers0