AlgoQuant
AlgoQuant

Reputation: 63

Replacing Values in a R Dataframe if another Dataframe value is Less than 0

I have two dataframes in r with the same size. What I want to do, is remove the value of the first dataframe, if the 2nd dataframe has a value less than zero

for example, if killer_stock dataframe has values less than 0, values in rank_stock would be replaced with NA

stock <-c('1','2','3')
stock2 <-c('1','2','3')

rank_stock <- data.frame(stock,stock2)

stockc <-c('-1','2','3')
stock2c <-c('2','-1','1')

killer_stock <- data.frame(stockc,stock2c)

the result dataframe would look something like below. but I have a very big dataframe and would also like to rm the value not replace it with chr "NA"

stock_r <-c('NA','2','3')
stock_r2 <-c('1','NA','3')

result_stock <- data.frame(stock_r,stock_r2)

Thank you for your help in advance!

Upvotes: 2

Views: 848

Answers (1)

astrofunkswag
astrofunkswag

Reputation: 2698

First of all, by putting quotes around the values in the vectors, the dataframes end up being columns of factors rather than numeric (if using the default stringsAsFactors system option). The first 2 lines of the code I enter below fixes that, but you could skip those if you enter the data differently.

I'll make use of the dplyr function mutate_all, but there are solutions with the base R family of apply functions which you might want to start with if you're new to R. There are many ways to implement a solution, but I am converting the killer_stock dataframe to 1 and NA if the value is above zero or below, respectively. Then I'm multiplying that dataframe element-wise with the rank_stock dataframe. NA times any number is any, so those values will get converted.

library(dplyr)
# Convert to numeric
killer_stock <- killer_stock %>% mutate_all(as.character) %>% mutate_all(as.numeric)
rank_stock <- rank_stock %>% mutate_all(as.character) %>% mutate_all(as.numeric)

# Convert to 1 or NA
df <- killer_stock %>% mutate_all(funs(ifelse(. < 0, NA, 1)))

# Element-wise multiplication
rank_stock * df

  stock stock2
1    NA      1
2     2     NA
3     3      3

Upvotes: 2

Related Questions