Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...