Reputation: 33
I have already know the rows and columns after matching the condition as follows: My data-set:
Power | Channel | Speed | Speed2 | Speed3
50 | 1 | 400 | 200 | 100
50 | 6 | 400 | 500 | 80
50 | 6 | 400 | 500 | 800
and I want to create a new column where it matches my condition where if all column speed >= 100
, return those rows. For example:
Power | Channel | Speed | Speed2 | Speed3 | Flag
50 | 1 | 400 | 200 | 100 | 1
50 | 6 | 400 | 500 | 80 | 1
I already knows the return rows and columns using this code:
which(blk13fullpower <= 100, arr.ind = TRUE)
which gives the output of:
row col
[1,] 1 1
[2,] 2 1
[3,] 3 1
[4,] 4 1
[5,] 5 1
[6,] 6 1
[7,] 7 1
However, I do not know how to flag my dataframe based on my results. Can someone help me, please?
Upvotes: 2
Views: 7664
Reputation: 389235
There are various ways to do this
cols <- grep("^Speed", names(df))
df[rowSums(df[cols] <= 100, na.rm = TRUE) > 0, ]
with apply
df[apply(df[cols] <= 100, 1, any), ]
Or with dplyr
library(dplyr)
df %>% filter_at(vars(starts_with("Speed")), any_vars(. <= 100))
If you want to add a new column with flag = 1
with base R solutions you can use transform
transform(df[rowSums(df[cols] <= 100, na.rm = TRUE) > 0, ], flag = 1)
or mutate
with dplyr
df %>%
filter_at(vars(starts_with("Speed")), any_vars(. <= 100)) %>%
mutate(flag = 1)
Upvotes: 2
Reputation: 2770
Try ifelse
blk13fullpower$flag <- ifelse ( blk13fullpower$Speed >100 & blk13fullpower$Speed2 > 100 & blk13fullpower$Speed3 >100 , 1 , 0)
Its easier if you provide some data using the dput command.
Upvotes: 1