Polar Bear
Polar Bear

Reputation: 731

How to subtract a column values conditional on another column

I have a dataset where I want to substract q.ret of quartile 4 from q.ret of quartile 1 for every index value: Below is my code to do the task:

q8<-  q7%>%  group_by(Index)%>%  summarise(ls =(subset(q7,quartile==1,select=c(q.ret))-subset(q7,quartile==4,select=c(q.ret))))

But it gives the following error

Error: expecting a single value

Please suggest something how to solve the problem. Thanks

Upvotes: 1

Views: 770

Answers (1)

akrun
akrun

Reputation: 886948

I guess this should work

q7%>%  
  group_by(Index)%>%  
  summarise(val =q.ret[quartile==1]-q.ret[quartile==4])

The subset(q7, part is getting the value of 'q.ret' (where quartile==1) based on the entire dataset and not within each 'Index'. For that we just need to subset 'q.ret' based on the logical index (quartile ==1 or quartile == 4).

Upvotes: 2

Related Questions