Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R check equality of one column to rowSums of other columns

I have a dataframe like this:

x y x1 y1 x2 y2 x3 y3
1 0 1 0 0 0 0 0
0 0 3 0 0 0 0 0
2 0 0 0 0 0 2 0
1 0 0 0 1 0 0 0

I want to find rows that x=x1+x2+x3 and rows that y=y1+y2+y3.
Here is my code to check x=x1+x2+x3:

col_x = c(3,5,7)
df[df$x == rowSums(df[col_x])]

Suppose return row 1,3,4, but it returned

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  x x1 y1 x2 x3 y3
1 1  1  0  0  0  0
2 0  3  0  0  0  0
3 2  0  0  0  2  0
4 1  0  0  1  0  0

I also tried

col_x = c(3,5,7)
df[df$x == apply(df[col_x],1,sum)]

Which also give me:

  x x1 y1 x2 x3 y3
1 1  1  0  0  0  0
2 0  3  0  0  0  0
3 2  0  0  0  2  0
4 1  0  0  1  0  0

I can’t figure out why it returned all rows and it had skip column y2.

>Solution :

You are just missing a comma.

col_x = c(3,5,7)
df[df$x == rowSums(df[col_x]),]

  x y x1 y1 x2 y2 x3 y3
1 1 0  1  0  0  0  0  0
3 2 0  0  0  0  0  2  0
4 1 0  0  0  1  0  0  0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading