Skip to content
Prev 307008 / 398506 Next

R help - Adding a column in a data frame with multiple conditions

Hi Libby,

You had an accumulation of small errors, from an extra ) to an unclear
understanding of how indexing works in R. Also, you shouldn't call
your dataframe df, or use square brackets in column names.

That said, what about:


sampledata <- structure(list(A = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L,
3L), B = c("X",
"Y", "Z", "X", "Y", "Z", "X", "Y", "Z"), C = c(90L, 72L, 67L,
74L, 42L, 81L, 92L, 94L, 80L), D = c(88L, 70L, 41L, 49L, 50L,
56L, 59L, 80L, 82L)), .Names = c("A", "B", "C", "D"), class =
"data.frame", row.names = c(NA,
-9L))

E <-
ifelse((sampledata$A == 1) & (sampledata$B == "X"), sampledata$C,
ifelse((sampledata$A == 1) & (sampledata$B == "Y"), sampledata$D,
ifelse((sampledata$A == 1) & (sampledata$B == "Z"),  sampledata$C, NA)))

sampledata <- data.frame(sampledata, E)

Sarah
On Thu, Oct 4, 2012 at 2:47 PM, Libby M Gertken <libbymg at utexas.edu> wrote: