anyway01
anyway01

Reputation: 33

How to set NAs under the condition that another column contains a specified string?

I have a data frame with the following information:

test_01 <- data.frame(Party_1 = c("ABC", "ABC", "ABC"),
                      Party_2 = c("DEF", "DEF", "GHI"),
                      Party_3 = c("GHI", "Independent", "Independent"),
                      Ministry_No_P1 = c(12,10,10),
                      Ministry_No_P2 = c(6,5,2),
                      Ministry_No_P3 = c(2,1,1)
                      )
test_01

I am now looking for a way to set the number of ministries (Ministry_No_Px) of the respective Party_x on NA whenever in a Party_x column a string named "Independent" is found.

I want to link the setting of Ministry_No_Px to NA on the condition of finding an "Independent" string in Party_x.

Upvotes: 2

Views: 37

Answers (1)

akrun
akrun

Reputation: 887531

Assuming the columns are corresponding order, create a logical matrix with the string columns i.e. column index from 1 to 3, and use that to assign the corresponding values in numeric column 4 to 6 as NA

test_01[4:6][test_01[1:3] == 'Independent'] <- NA

-output

test_01
#  Party_1 Party_2     Party_3 Ministry_No_P1 Ministry_No_P2 Ministry_No_P3
#1     ABC     DEF         GHI             12              6              2
#2     ABC     DEF Independent             10              5             NA
#3     ABC     GHI Independent             10              2             NA

Upvotes: 2

Related Questions