Reputation: 1141
Is there an intuitive way to replace values in two columns of a data frame if patterns in one column of the same differ from the desired one? Specifically, my data frame looks like:
Col1 Value1 Value2
my_HD_SAMPLE 34 0.34
my_HD_T_SAMPLE 6 0.6
my_BD_NAME 94 0.94
my_LE_NAME 1 0.1
my_TS_SAMPLE 74 0.74
I would like to replace the values in columns 2 and 3 with 0 if the row in Col1 does not match the pattern BD|HD
. The desired output should be:
Col1 Value1 Value2
my_HD_SAMPLE 34 0.34
my_HD_T_SAMPLE 6 0.6
my_BD_NAME 94 0.94
my_LE_NAME 0 0
my_TS_SAMPLE 0 0
I tried this:
mydf = mydf$"Col1"[!grepl('BD|HD',mydf$"Col1")] <- 0
And I got this warning message:
In [<-.factor`(`*tmp*`, !grepl("BD|HD", mydf$Col1), value = c(`NA` = NA, :
invalid factor level, NA generated
How can I solve this problem?
Upvotes: 0
Views: 784
Reputation: 343
Seems to me Col1 is a factor. Try:
# Convert to character first.
rows <- !grepl("BD|HD", as.character(mydf$`Col1`))
mfdf$`Value1`[rows] <- 0
mfdf$`Value2`[rows] <- 0
Upvotes: 1
Reputation: 2949
Try This
mydf[!grepl('BD|HD',mydf$"Col1"),][2:ncol(mydf)] <- 0
> mydf
Col1 Value1 Value2
1 my_HD_SAMPLE 34 0.34
2 my_HD_T_SAMPLE 6 0.60
3 my_BD_NAME 94 0.94
4 my_LE_NAME 0 0.00
5 my_TS_SAMPLE 0 0.00
Upvotes: 0