创建一个循环以在R中生成一系列数据帧



我有一个df,我想得到每个批次在每个持续时间内X1、X2、X3的平均值和sd。

batch, duration, X1, X2, X3 
B1, 0, 0.1, 0.1, 0.2 
B1, 1, 0.2, 0.15, 0.15 
B1, 2, 0.3, 0.2, 0.1 
B2, 0, 0.1, 0.1, 0.2 
B2, 1, 0.1, 0.1, 0.2 
B2, 2, 0.1, 0.1, 0.2

我只能按照下面的手动完成

s1 <- summarySE(data = df, "X1", groupvars = c("duration"), na.rm = FALSE, conf.interval = 0.95, .drop = TRUE)
s2 <- summarySE(data = df, "X2", groupvars = c("duration"), na.rm = FALSE, conf.interval = 0.95, .drop = TRUE)
s3 <- summarySE(data = df, "X3", groupvars = c("duration"), na.rm = FALSE, conf.interval = 0.95, .drop = TRUE)

我想问一下,我如何创建一个循环,一次自动获得X1、X2、X3的摘要?

base解决方案:

to_use <-names(df)[grepl("^X",names(df))]
Map(function(x) Rmisc::summarySE(df,x,groupvars = c("duration"),
na.rm = FALSE,
conf.interval = 0.95, .drop = TRUE),to_use)

lapply:

lapply(to_use,function(x) Rmisc::summarySE(df,x,groupvars = c("duration"),
na.rm = FALSE,
conf.interval = 0.95, .drop = TRUE) ) 

结果:

$X1
duration N   X1         sd   se        ci
1        0 2 0.10 0.00000000 0.00 0.0000000
2        1 2 0.15 0.07071068 0.05 0.6353102
3        2 2 0.20 0.14142136 0.10 1.2706205
$X2
duration N    X2         sd    se        ci
1        0 2 0.100 0.00000000 0.000 0.0000000
2        1 2 0.125 0.03535534 0.025 0.3176551
3        2 2 0.150 0.07071068 0.050 0.6353102
$X3
duration N    X3         sd    se        ci
1        0 2 0.200 0.00000000 0.000 0.0000000
2        1 2 0.175 0.03535534 0.025 0.3176551
3        2 2 0.150 0.07071068 0.050 0.6353102

数据:

df <- structure(list(batch = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("B1", 
"B2"), class = "factor"), duration = c(0L, 1L, 2L, 0L, 1L, 2L
), X1 = c(0.1, 0.2, 0.3, 0.1, 0.1, 0.1), X2 = c(0.1, 0.15, 0.2, 
0.1, 0.1, 0.1), X3 = c(0.2, 0.15, 0.1, 0.2, 0.2, 0.2)), class = "data.frame", row.names = c(NA, 
-6L))

相关内容

  • 没有找到相关文章

最新更新