Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create binary column (0/1) based on condition in another column

Tags:

r

I have a column of data in a data frame

Ozone   Solar.R Wind    Temp    Month   Day
41  190 7.4 67  5   1
36  118 8   72  5   2
12  149 12.6    74  5   3
18  313 11.5    62  5   4
NA  NA  14.3    56  5   5
28  NA  14.9    66  5   6
23  299 8.6 65  5   7
19  99  13.8    59  5   8
8   19  20.1    61  5   9
NA  194 8.6 69  5   10
7   NA  6.9 74  5   11
16  256 9.7 69  5   12
11  290 9.2 66  5   13
14  274 10.9    68  5   14
18  65  13.2    58  5   15

I need to Change the Temp column to 1 or 0 based on a condition if it is greater than 70. So I need a column with 1 when the Temp is greater than 70 and 0 when it is less so I can do a regression using the Temp as a binary variable.

R will take the condition statement

cfv <- mydata$Temp
x <- cfv > 70 
for(i in nrow(cfv)) {if(x = TRUE) {1} else if(x = FALSE) {0}

but I can't get any further and use it to create a new column.

like image 487
user2907249 Avatar asked Nov 29 '22 00:11

user2907249


1 Answers

You can also use ifelse which is vectorized if-else function

mydata$NewTemp <- ifelse(mydata$Temp>0, 1, 0)
like image 65
CHP Avatar answered Jan 30 '23 21:01

CHP