用前一行值填充数据帧 [英] Filling data frame with previous row value
问题描述
我有一个数据框有2列。
column1在
中有随机数列column2是一个占有列的位置,我希望column3看起来像
随机temp
0.502423373 1
0.687594055 0
0.741883739 0
0.445364032 0
0.50626137 0.5
0.516364981 0
...
I要填充column3,所以它需要最后一个非零数字(在本示例中为1或.5),并连续填充以下数据行,直到它以不同的数字进行排列。那么它会重复整个列的过程。
随机临时状态
/ pre>
0.502423373 1 1
0.687594055 0 1
0.741883739 0 1
0.445364032 0 1
0.50626137 0.5 0.5
0.516364981 0 0.5
0.807804708 0 0.5
0.247948445 0 0.5
0.46573337 0 0.5
0.103705154 0 0.5
0.079625868 1 1
0.938928944 0 1
0.677713019 0 1
0.112231619 0 1
0.165907178 0 1
0.836195267 0 1
0.387712998 1 1
0.147737077 0 1
0.439281543 0.5 0.5
0.089013503 0 0.5
0.84174743 0 0.5
0.931738707 0 0.5
0.807955172 1 1
感谢任何和所有帮助
解决方案也许你在0值设置为
NA
之后,可以使用zoo包中的na.locf
。假设您的data.frame
被称为mydf:mydf $状态< - mydf $ temp
mydf $ state [mydf $ state == 0]< - NA
库(zoo)
mydf $ state< - na。 locf(mydf $ state)
#随机临时状态
#1 0.5024234 1.0 1.0
#2 0.6875941 0.0 1.0
#3 0.7418837 0.0 1.0
#4 0.4453640 0.0 1.0
#5 0.5062614 0.5 0.5
#6 0.5163650 0.0 0.5
如果您的原始
data.frame
中的temp中有NA
列,并且您希望将它们保存为新生成的状态列中的NA
,这很容易处理。再添加一行以重新引入NA
值:mydf $状态[is.na(mydf $ temp)]< - NA
I have a data frame that has 2 columns.
column1 has random numbers in column2 is a place holding column for what i want column3 to look like
random temp 0.502423373 1 0.687594055 0 0.741883739 0 0.445364032 0 0.50626137 0.5 0.516364981 0 ...
I want to fill column3 so it takes the last non-zero number (1 or .5 in this example) and continuously fills the following rows with that value until it hits a row with a different number. then it repeats the process for the entire column.
random temp state 0.502423373 1 1 0.687594055 0 1 0.741883739 0 1 0.445364032 0 1 0.50626137 0.5 0.5 0.516364981 0 0.5 0.807804708 0 0.5 0.247948445 0 0.5 0.46573337 0 0.5 0.103705154 0 0.5 0.079625868 1 1 0.938928944 0 1 0.677713019 0 1 0.112231619 0 1 0.165907178 0 1 0.836195267 0 1 0.387712998 1 1 0.147737077 0 1 0.439281543 0.5 0.5 0.089013503 0 0.5 0.84174743 0 0.5 0.931738707 0 0.5 0.807955172 1 1
thanks for any and all help
解决方案Perhaps you can make use of
na.locf
from the "zoo" package after setting values of "0" toNA
. Assuming yourdata.frame
is called "mydf":mydf$state <- mydf$temp mydf$state[mydf$state == 0] <- NA library(zoo) mydf$state <- na.locf(mydf$state) # random temp state # 1 0.5024234 1.0 1.0 # 2 0.6875941 0.0 1.0 # 3 0.7418837 0.0 1.0 # 4 0.4453640 0.0 1.0 # 5 0.5062614 0.5 0.5 # 6 0.5163650 0.0 0.5
If there were
NA
values in your originaldata.frame
in the "temp" column, and you wanted to keep them asNA
in the newly generated "state" column too, that's easy to take care of. Just add one more line to reintroduce theNA
values:mydf$state[is.na(mydf$temp)] <- NA
这篇关于用前一行值填充数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!