I have a dataframe as follows
Sol_name    geo_pos     loc_pos     dol_pos    pol_pos   kol_pos
A            1            1          0          0         1
B            0            1          1          0         0
C            1            0          1          1         1
D            0            1          0          0         1
I need to create a function where the user can input column names into a vector and the dataframe will get filtered where value in any of those columns is 1
Example: If the input is col_nm = c("geo_pos","dol_pos") then the output I am looking for is
Sol_name    geo_pos     loc_pos     dol_pos    pol_pos   kol_pos
A            1            1          0          0         1
B            0            1          1          0         0
C            1            0          1          1         1
Is there any efficient way to do this?
data
df <- read.table(text="Sol_name    geo_pos     loc_pos     dol_pos    pol_pos   kol_pos
A            1            1          0          0         1
B            0            1          1          0         0
C            1            0          1          1         1
D            0            1          0          0         1",h=T)
                We can use rowSums efficiently here to filter rows which has at least one "1" in the selected columns.
get_one_rows <- function(cols) {
    df[rowSums(df[cols] == 1) > 0, ]
}
col_nm = c("geo_pos","dol_pos")
get_one_rows(col_nm)
# Sol_name geo_pos loc_pos dol_pos pol_pos kol_pos
#1        A       1       1       0       0       1
#2        B       0       1       1       0       0
#3        C       1       0       1       1       1
col_nm = c("kol_pos")
get_one_rows(col_nm)
#  Sol_name geo_pos loc_pos dol_pos pol_pos kol_pos
#1        A       1       1       0       0       1
#3        C       1       0       1       1       1
#4        D       0       1       0       0       1
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With