开发者

Conditional update of dataframe

Folks, I have an hourly temperature data like this

Lines <- "D开发者_如何学JAVAate,Outdoor,Indoor
 01/01  01:00:00,24.5,21.3
 01/01  02:00:00,24.3,21.1
 01/01  03:00:00,24.1,21.1
 01/01  04:00:00,24.1,20.9
 01/01  05:00:00,25.,21.
 01/01  06:00:00,26.,21.
 01/01  07:00:00,26.6,22.3
 01/01  08:00:00,28.,24.
 01/01  09:00:00,28.9,26.5
 01/01  10:00:00,29.4,29
 01/01  11:00:00,30.,32.
 01/01  12:00:00,33.,35.
 01/01  13:00:00,33.4,36
 01/01  14:00:00,35.8,38
 01/01  15:00:00,32.3,37
 01/01  16:00:00,30.,34.
 01/01  17:00:00,29.,33.
 01/01  18:00:00,28.,32.
 01/01  19:00:00,26.3,30
 01/01  20:00:00,26.,28.
 01/01  21:00:00,25.9,25
 01/01  22:00:00,25.8,21.3
 01/01  23:00:00,25.6,21.4
 01/01  24:00:00,25.5,21.5
 01/02  01:00:00,25.4,21.6
 01/02  02:00:00,25.3,21.8"

And I need to create another column that says 1 if the Indoor is higher than the Outdoor by at least 1 degree.

I tried:

DF$Time = 0
if ((Indoor-Outdoor) >= 1) DF$Time = 1

But the above does not work. Any suggestion?


You could also reduce the logic to a boolean value as such:

#using mdsummer's DF object:
y <- with(DF, (Indoor - Outdoor >= 1) * 1)

x <- ifelse(test = (DF$Indoor - DF$Outdoor) >= 1, yes = 1, no = 0)

> all.equal(x,y)
[1] TRUE


Use ifelse for a vectorized comparison rather than if which is for single-element comparisons.

Also, first you should give reproducible code, but 'Lines' is just a character vector so

DF <- read.table(textConnection(Lines), sep = ",", header = TRUE)

Time can be added directly as the return value of ifelse, which gives 1 for when the comparison is true, and 0 otherwise.

DF$Time <- ifelse(test = (DF$Indoor - DF$Outdoor) >= 1, yes = 1, no = 0)

For the details on if requiring a single element see help(Control):

cond: A length-one logical vector that is not ‘NA’. Conditions of length greater than one are accepted with a warning, but only the first element is used. Other types are coerced to logical if possible, ignoring any class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜