r - Edit values from a variable based on multiple values from multiple variable within a dataframe -


i new r please bear me.

i have dataframe of 8891 obs. of 4 variables:

survived: int  0 1 1 0 0 0 0 1 1 ... sex       : factor w/ 2 levels "female","male": 2 1 1 1 2 2 2 2 1 1 ... age      : num  22 38 15 78 35 na 54 2 27 14 ... fare : num  120 120 120 120 ...  sex <- c("female","male", "male", "male") survive <- c(0,1,1,0) age <- c(22,38,15,78) fare <- c(120,120,120,120) dataframe <- data.frame(sex, survive, age, fare) #view(dataframe) 

i trying create variable fixedfare values variable fare divided 2 based on values variable survived , variable age.

basically, if value in survived 1 , value in age <= 16 , >= 60 divide value x in fare 2. , if comes across na mark na. within same data frame.

i not sure how this. i’ve searched related questions in stackoverflow solution couldn’t find 1 similar question.

thanks help.

the ifelse approach assigns values based on conditions provided:

df$fare <- ifelse(df$survived == 1 & (df$age <= 16 | df$age >= 60), df$fare/2, df$fare) 

using example in question wrap function call in transform:

transform(dataframe, fare = ifelse(survive == 1 & (age <= 16 | age >= 60), fare/2, fare)) #     sex survive age fare #1 female       0  22  120 #2   male       1  38  120 #3   male       1  15   60 #4   male       0  78  120 

Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -