1

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?

0

2 Answers 2

2

The following would do the trick

df <- 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))

x <- rowSums(df[, grep("and", tolower(colnames(df)))], na.rm = TRUE)
Sign up to request clarification or add additional context in comments.

1 Comment

rowSums(df[grepl("and", names(df), ignore.case=TRUE)], na.rm=TRUE) as a base R translation.
1
colnames(names1) <- tolower(colnames(names1))

will rid you for the need for permutations

names1$x <- rowSums(names1[which(grepl('and', colnames(names1)))], na.rm = TRUE)

1 Comment

which(grepl(...)) can simply be grep()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.