user10830454
user10830454

Reputation:

R - If statement function to set value of new column

I have 2 columns pos and neg, each with a integer value.

I would like to create a new column score, with each element of this column given a value of:

What would be the best way to do this? I am new to creating functions in R, so any help or direction is appreciated.

Upvotes: 1

Views: 39

Answers (1)

akrun
akrun

Reputation: 886938

We can use ifelse instead of if/else as ifelse is vectorized

df1$score <- with(df1, ifelse(pos > neg, 1, ifelse(pos < neg, -1, 0)))

Or get the difference of 'pos' and 'neg' and apply sign which will give values -1, 0, 1 when the sign is negative, value 0 or positive

df1$score <- with(df1, sign(pos - neg ))

data

df1 <- data.frame(pos = c(5, 4, 3, 1, 2), neg = c(5, 3, 4, 1, 3))

Upvotes: 2

Related Questions