I have multiple variable names that I need to combine into a single variable based on a common string of text. My sample data are:
structure(list(And = c(10L, NA, 10L), and = c(20L, 10L, 10L),
andbc = c(1L, NA, NA), baNdc = c(4L, NA, 5L), ban = c(1L,
NA, 1L)), .Names = c("And", "and", "andbc", "baNdc", "ban"), class = "data.frame", row.names = c(NA, -3L))
I would like to create a new variable x, the value of which would be a row sum of the values of the other variables that share the common text string "and" ignoring the case of any of the letters in that string.
I attempted creating the variable by specifying the permutations, which I'm hoping to avoid:
names1[, 1:5][is.na(names1[, 1:5])] <- 0
names1$x <- sum(names1[which(grepl("And|and|aNd", names(names1)))])
The result I get for values of x is a sum total of all values for the variables that meet the text string criteria:
structure(list(And = c(10, 0, 10), and = c(20L, 10L, 10L), andbc = c(1, 0, 0), baNdc = c(4, 0, 5), ban = c(1, 0, 1), x = c(70, 70, 70)), .Names = c("And", "and", "andbc", "baNdc", "ban", "x"), row.names = c(NA, -3L), class ="data.frame"
How can I obtain the row sums based on the text string criteria and avoid having to specify the permutations of upper or lower case?