我正在尝试为基于系统的生态模型准备输入数据。我目前有一个名为“ Precip”的数据框,其中有64列,每列“ X1”,“ X2”,“ X3”等都是30年的每日降水数据模型(请参见下文)。我需要将每个模型都放在彼此的顶部,所以我将所有数据堆叠在一起排成一行。但是,在每个模型之间,我都需要添加填充物降水数据,该数据仅为0天降水的365天(见下文)。从本质上讲,我需要创建一个数据框或列表为rbind(X1,FillerPrecip,X2,FillerPrecip,X3,FillerPrecip等)。
我尝试过将Precip和FillerPrecip都转换为列表并使用rbindlist,但是不允许我在Precip的每个元素之间绑定FillerPrecip。
> str(Precip)
'data.frame': 11322 obs. of 64 variables:
$ X1 : num 0.11 0 0 0 0 ...
$ X2 : num 0 0 0 0 0 ...
$ X3 : num 0.3437 0.1464 0 0 0.0422 ...
$ X4 : num 0 0 0 0 0 0 0 0 0 0 ...
$ X5 : num 0 0 0 0 0 ...
$ X6 : num 0 0 0.0304 0 0 ...
> head(FillerPrecip)
V1
1 0
2 0
3 0
4 0
5 0
6 0
答案 0 :(得分:1)
请考虑将数据的形状从宽变长。然后按X
组,rbind
模型的每个子集:
# RESHAPE LONG
rdf <- reshape(df, varying = list(names(df)), times = names(df),
timevar = "X", v.names = "FillerPrecip",
new.row.names = 1:1E4, direction = "long")
# BY GROUP: rbind 365 ROWS OF ZERO INTO FillerPrecip COLUMN
df_list <- by(rdf, rdf$X, function(sub)
rbind(sub, data.frame(X=NA, FillerPrecip = rep(0, 365), id = NA))
)
# CONCATENATE INDIVIDUAL DFs INTO MASTER DF
final_df <- do.call(rbind, unname(df_list))
答案 1 :(得分:0)
尝试以下操作:
PrecipVector <- c(sapply(seq_along(Precip), function(i) {
c(Precip[,i], FillerPrecip)
}))
这将在FillerPrecip
的每一列之后插入Precip
。结果将是一个数字矢量,您可以根据需要将其转换为数据框或列表。