R 基于单个信息生成新的数据集

R 基于单个信息生成新的数据集,r,R,我有这样一个数据集: df <- data.frame(ID=1:10, baseline = c(1.8,2.4,3.2,2.3,2.1,2.2,3,2.8,2,2.9)) 因此,对于每个ID,应该生成241个响应。如何生成包含ID、基线、时间和响应的新数据集 试试看 library(reshape2) res <- melt(apply(df[,2, drop=FALSE], 1, function(x) x+0.5*sin(2*3.14*(t-7.5)

我有这样一个数据集:

df <- data.frame(ID=1:10, baseline = c(1.8,2.4,3.2,2.3,2.1,2.2,3,2.8,2,2.9))
因此,对于每个ID,应该生成241个响应。如何生成包含ID、基线、时间和响应的新数据集

试试看

library(reshape2)
res <- melt(apply(df[,2, drop=FALSE], 1, 
           function(x) x+0.5*sin(2*3.14*(t-7.5)/24)))

indx <- rep(1:nrow(df), each=241)


df1 <- cbind(df[indx,], time= rep(t, nrow(df)), response=res[,3])
row.names(df1) <- NULL
dim(df1)
#[1] 2410    4

head(df1,3)
#  ID baseline time response
#1  1      1.8  0.0 1.337870
#2  1      1.8  0.1 1.333034
#3  1      1.8  0.2 1.328518
library(重塑2)
res另一种方法:

t <- rep(seq(0, 24, by = 0.1), each = nrow(df))
vals <- 0.5 * sin(2 * 3.14 * (t - 7.5) / 24)
new_df <- cbind(df, t, response = df$baseline + vals)

t在
apply
功能中
1
是什么意思?这是否意味着函数应用于行?@dzadi
1
apply
MARGIN
。在这里,我只是对
apply
@dzadi生成的输出使用
melt
,以澄清akrun的评论:是的,函数应用于每一行。
t <- seq(0,24, by=0.1)
indx <- rep(1:nrow(df), each=length(t))
df2 <- within(df[indx,], {response<-baseline+0.5*sin(2*3.14*(t-7.5)/24)
                          time <- t})

row.names(df2) <- NULL
all.equal(df1, df2)
#[1] TRUE
t <- rep(seq(0, 24, by = 0.1), each = nrow(df))
vals <- 0.5 * sin(2 * 3.14 * (t - 7.5) / 24)
new_df <- cbind(df, t, response = df$baseline + vals)