我有以下列表:
result_list
[[1]]
[1] 0.941000 6.039348 0.930000 5.500994
[[2]]
[1] 0.951000 5.696640 0.933000 5.314214
[[3]]
[1] 0.952000 5.989865 0.943000 5.489865
[[4]]
[1] 0.938000 5.456050 0.935000 5.460618
[[5]]
[1] 0.954000 6.254546 0.941000 5.648242
我为每一列加了元素:
Reduce("+",result_list)
[1] 4.73600 29.43645 4.68200 27.41393
并计算出平均值:
means=Reduce("+",result_list)/length(result_list)
means
[1] 0.947200 5.887290 0.936400 5.482787
问题:我该如何减去刚为初始列表(result_list)的相应元素计算出的每个均值?
答案 0 :(得分:2)
lapply(result_list, function(x) x - means)
# [[1]]
# [1] -0.0062000 0.1520582 -0.0064000 0.0182074
#
# [[2]]
# [1] 0.0038000 -0.1906498 -0.0034000 -0.1685726
#
# [[3]]
# [1] 0.0048000 0.1025752 0.0066000 0.0070784
#
# [[4]]
# [1] -0.0092000 -0.4312398 -0.0014000 -0.0221686
#
# [[5]]
# [1] 0.0068000 0.3672562 0.0046000 0.1654554
数据:
result_list <- list(
c(0.941000,6.039348,0.930000,5.500994),
c(0.951000,5.696640,0.933000,5.314214),
c(0.952000,5.989865,0.943000,5.489865),
c(0.938000,5.456050,0.935000,5.460618),
c(0.954000,6.254546,0.941000,5.648242)
)
答案 1 :(得分:1)
另一种方法是绑定所有列表以创建矩阵:
matr <- do.call(cbind, result_list)
matr - rowMeans(matr)
[,1] [,2] [,3] [,4] [,5]
[1,] -0.0062000 0.0038000 0.0048000 -0.0092000 0.0068000
[2,] 0.1520582 -0.1906498 0.1025752 -0.4312398 0.3672562
[3,] -0.0064000 -0.0034000 0.0066000 -0.0014000 0.0046000
[4,] 0.0182074 -0.1685726 0.0070784 -0.0221686 0.1654554
答案 2 :(得分:0)
您可以使用rapply
。
rapply(result_list, `-`, y=Reduce(`+`, result_list)/length(result_list), how="l")
或以下 @Cole:
rapply(result_list, `-`, y=colMeans(do.call(rbind, result_list)), how="l")
# [[1]]
# [1] -0.0062000 0.1520582 -0.0064000 0.0182074
#
# [[2]]
# [1] 0.0038000 -0.1906498 -0.0034000 -0.1685726
#
# [[3]]
# [1] 0.0048000 0.1025752 0.0066000 0.0070784
#
# [[4]]
# [1] -0.0092000 -0.4312398 -0.0014000 -0.0221686
#
# [[5]]
# [1] 0.0068000 0.3672562 0.0046000 0.1654554
数据
result_list <- list(c(0.941, 6.039348, 0.93, 5.500994), c(0.951, 5.69664, 0.933,
5.314214), c(0.952, 5.989865, 0.943, 5.489865), c(0.938, 5.45605,
0.935, 5.460618), c(0.954, 6.254546, 0.941, 5.648242))
答案 3 :(得分:0)
或使用map
中的purrr
library(purrr)
map(result_list, ~ .x - means)
#[[1]]
#[1] -0.0062000 0.1520582 -0.0064000 0.0182074
#[[2]]
#[1] 0.0038000 -0.1906498 -0.0034000 -0.1685726
#[[3]]
#[1] 0.0048000 0.1025752 0.0066000 0.0070784
#[[4]]
#[1] -0.0092000 -0.4312398 -0.0014000 -0.0221686
#[[5]]
#[1] 0.0068000 0.3672562 0.0046000 0.1654554
或更紧凑
map(result_list, `-`, means)