gpt4 book ai didi

r - for循环R中向量的特定元素

转载 作者:行者123 更新时间:2023-12-05 01:34:08 24 4
gpt4 key购买 nike

我想运行一个 for 循环,它只对数据框中列中的特定元素进行计算。这些元素是从矩阵中的相邻列引用的。我可以通过直观观察哪些元素对应于值来做到这一点——例如for(i in 1:5){ # 在一个包含 301 个元素的列中。但是,我希望能够在没有元素编号的先验知识的情况下指定它。

例如在下面的数据框中,当 data.LICOR$day.night=='d' 时,我想在 data.LICOR$flux 列的元素上运行 for 循环

   data.LICOR.day.night data.LICOR.flux
1 d 26.89
2 d 27.89
3 d 28.77
4 d 28.92
5 d 29.30
6 n 28.51
7 n 28.98
8 n 28.41
9 n 27.87
10 n 28.18

这是我之前的代码通过指定分别对应于 day.night = 'd' 和 day.night ='n' 的元素 1:5 和 6:10 所做的

# replace day fluxes
for(i in 1:5){
if(data.LICOR$flux[i] > av.day.flux+2*sd.day.flux)
data.LICOR$flux[i] <- av.day.flux
else if(data.LICOR$flux[i] < av.day.flux-2*sd.day.flux)
data.LICOR$flux[i] <- av.day.flux
}

# replace night fluxes
for(i in 6:10){
if(data.LICOR$flux[i] > av.night.flux+2*sd.night.flux)
data.LICOR$flux[i] <- av.night.flux
else if(data.LICOR$flux[i] < av.night.flux-2*sd.night.flux)
data.LICOR$flux[i] <- av.night.flux
}

这会删除与平均值相差大于 2 个标准差的值,并用平均值替换它们。

感谢您的任何建议。

最佳答案

考虑到您对 Gavin 回答的评论中的循环,我认为您想要这样的东西(假设您的示例数据位于名为 data.LICOR 的对象中)。

# within() allows us to evaluate all the expressions (the 2nd argument)
# using the data in 'data.LICOR'.
data.LICOR <- within(data.LICOR, {
# ave() applies 'FUN' to the subsets of 'flux' specified by 'day.night'
# and returns an object the same length as 'flux'.
av.flux <- ave(flux, day.night, FUN=mean);
sd.flux <- ave(flux, day.night, FUN=sd);
# ifelse() returns 'av.flux' when the first argument is TRUE
# and 'flux' when it's FALSE.
flux <- ifelse(flux > av.flux+2*sd.flux |
flux < av.flux-2*sd.flux, av.flux, flux) })

关于r - for循环R中向量的特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5146082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com