5

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.

0

2 Answers 2

14

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

mydata$NewTemp <- ifelse(mydata$Temp>0, 1, 0)
Sign up to request clarification or add additional context in comments.

Comments

12

You're over-thinking things. TRUE and FALSE can be coerced to 1 and 0 respectively by using as.numeric.

mydf$Temp > 70
# [1] FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE
as.numeric(mydf$Temp > 70)
# [1] 0 1 1 0 0 0 0 0 0 0 1 0 0 0 0

So, to create the new column, you can simply do:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.