[英]Retain previous data frame based on condition in R
So I'm trying to update or retain a dataframe df2
based on a certain condition of another data frame df1
. 所以我试图根据另一个数据帧
df1
的特定条件来更新或保留数据帧df2
。
For Example, Assuming df1
get updated for every 30 seconds, so if the number of rows in df1
ie nrow(df1)!= 0
then df2 <- df1
else if retain the previous values in df2
. 例如,假设
df1
每30秒更新一次,那么如果 df1
的行数即nrow(df1)!= 0
则df2 <- df1
nrow(df1)!= 0
如果保留df2
的先前值。
NOTE: On the first iteration, df2
can be initialized to a NULL
dataframe. 注意:在第一次迭代中,可以将
df2
初始化为NULL
数据帧。
Following is my code 以下是我的代码
#Initializing df2 as empty dataframe
df2 <- data.frame(weight = integer(),stringAsFactors = FALSE)
#Condition to check if number of rows in df1 != 0
if(nrow(df1) != 0){
df2 <- df1
temp <- df1 #Another copy of df1
}
else{
df2 <- temp
}
Here I created an another data frame called temp
to keep a copy of df1
so that it can be used when nrow(df1) == 0
. 在这里,我创建了另一个名为
temp
数据框,以保留df1
的副本,以便在nrow(df1) == 0
时可以使用它。 I don't know if the usage of temp
is correct or not. 我不知道
temp
的用法是否正确。
This code will create an empty dataframe named df2
. 此代码将创建一个名为
df2
的空数据df2
。 If nrow(df1)>0
then it will effectively assign the contents of df1
to df2
. 如果
nrow(df1)>0
,它将有效地将df1
的内容分配给df2
。 If nrow(df1)==0
then df2
remains empty. 如果
nrow(df1)==0
则df2
保持为空。
df2 <- data.frame()
if(nrow(df1)>0) df2 <- df1
I have a hard time imagining why this is useful. 我很难想象为什么这很有用。 If, perhaps, you intended to "grow"
df2
by appending on whatever is in df1
- which might be more common - then do something like this: 如果也许您打算通过附加
df1
来“增长” df2
(这可能更常见),则可以执行以下操作:
df2 <- data.frame()
if(nrow(df1)>0) df2 <- rbind(df2, df1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.