Home > Mobile >  How do I sum columns which contain a certain string in the column heading?
How do I sum columns which contain a certain string in the column heading?

Time:12-06

I have a dataframe containing a bunch of columns with the string "hsehold" in the headers, and a bunch of columns containing the string "away" in the headers. (eg. hsehold1, hsehold2, hsehold3, away1, away2, away3)

I want to add a column to the dataframe containing the sum of the values in all columns containing "hsehold" in the header.

This is the code I've tried:

df$newCol.hsehold <- rowSums(df, na.rm = TRUE, select(matches("hsehold"))) and df$newCol.hsehold <- rowSums(df, na.rm = TRUE, select(contains("hsehold")))

I get the error message: contains()` must be used within a selecting function.

CodePudding user response:

Try rowSums(df[,grepl("hsehold",colnames(df)]).

CodePudding user response:

I'm not sure how to upvote a comment on my question.

Ronak Shah commented (instead of adding an answer) to correct my code.

It was successful, thank you!

Here's what they suggested:

df$newCol.hsehold <- rowSums(select(df, matches("hsehold")), na.rm = TRUE)
  •  Tags:  
  • r
  • Related