0

I'm trying to dynamically create and assign values to variables of a particular data frame using a for loop. I want to create the object from an array of strings, add the word "Check" to the end, then continue assigning it. The problem is, I'm having trouble referring to the variable as an element of an object.

Probably easier to show than explain....

diffs$derp = c("this", "that", "the other")
diffs$herp = c("esa", "esto", "el otro")
for(i in ncol(derp)) {
  temp = paste0(derp[i], "Check")
  diffs$temp = ifelse(derp[i] == derp[i], "Equal", paste(derp[i], herp[i], sep=" =/= "))
}

The problem of course is that this code thinks that I'm referring to a variable in diffs called temp. I've seen the assign() function, but I don't see a way to add my new variable to a data frame with it.

EDIT: I'd like to get output like:

diffs$thisCheck = ifelse(diffs$this == diffs$that, "Equal",
                 paste(diffs$this, diffs$that, sep=" =/= "))
jamzsabb
  • 1,125
  • 2
  • 18
  • 40
  • 1
    Can you provide your desired output too please? – David Arenburg Dec 30 '15 at 18:46
  • When working with strings containing column names, use `[` not `$`. That is `diffs[, temp] = ...` will do what you want. See also `fortunes::fortune(312)` and `fortunes::fortune(343)`. – Gregor Thomas Dec 30 '15 at 18:55
  • Why the comma after the first bracket? – jamzsabb Dec 30 '15 at 18:58
  • The standard way to reference 2-dimensional data is `[rows, columns]`. Leaving rows blank implicitly means "all rows". Because data frames are lists, you can also do `diffs[[temp]]` or even `diffs[temp]` as well, but I prefer to be explicit about rows and columns (the only difference is style). – Gregor Thomas Dec 30 '15 at 19:01

0 Answers0