If Statements and logical operators in R -
i have dataframe money column , age group column.
the money column has nas , age group column has values range 1 5.
what want find sum of money column when agegroup column equals value. 5 example.
i have been attempting use if statement getting response "the condition has length > 1 , first element used".
if(df$agegroup == 5) sumofmoney <- sum(df$money)
my problem don't know how turn "if" "when". want sum money column when rows have agegroup value of 5, or 3, or whatever choose.
i believe have condition correct, add second if statement when calculating sum?
i use data.table
'by-group' operation.
library(data.table) setdt(df)[,list(sm=sum(money,na.rm=true)),agegroup]
this compute sum of money group. filtering result group value :
setdt(df)[,list(sm=sum(money,na.rm=true)),agegroup][agegroup==4]
Comments
Post a Comment