[英]Conditional update of dataframe
Folks, I have an hourly temperature data like this 伙计们,我有一个像这样的每小时温度数据
Lines <- "Date,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. 我需要创建另一列,如果“室内”比“室外”至少高1度,则说1。
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. 使用
ifelse
进行矢量化比较,而不是if
其用于单元素比较。
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. 可以将
Time
直接添加为ifelse
的返回值,如果比较为true,则返回1,否则返回0。
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): 有关
if
需要单个元素的详细信息,请参见help(Control):
cond: A length-one logical vector that is not 'NA'.
cond:不是'NA'的长度为1的逻辑向量。 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.
如果可能,其他类型将被强制转换为逻辑类型,而忽略任何类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.