R语言数据处理错误:na.approx() 函数引发“new”变量大小问题
The error message suggests that there is an issue with the size of the 'new' variable, which is being created using the 'na.approx()' function. Specifically, the error message indicates that the size of 'new' should be either 99 or 1, but it is currently 0.
One possible reason for this error is that there are no non-missing values of 'Flux' for a particular group of observations (defined by 'Gas', 'Hybrid', 'Nrate', and 'Plotnum'), which means that 'na.approx()' cannot impute missing values. To fix this, you could add a check to see if there are any non-missing values of 'Flux' before applying 'na.approx()', and only apply it if there are.
For example, you could modify the code as follows:
df <- dat %>%
filter(Flux != 'NA') %>%
mutate(Flux = Flux*60/100, #气体单位都是mg/min/m2,进行单位面积换算(kg/ha)
Date = as.Date(Date), #将POSIXct时间格式换为Date格式
Hybrid = factor(Hybrid, levels = c('ZD958','JNK728','DK653','XY335'))) %>%
select(1,3:9,19) %>%
group_by(Gas, Date, Hybrid, Nrate) %>%
mutate(Z = scale(Flux),
Flux = ifelse(abs(Z) > 1.15,
mean(Flux, na.rm = TRUE), Flux)) %>%
group_by(Gas, Hybrid, Nrate) %>%
complete(.[,c(3:5,8)],Date=seq(min(Date),max(Date),by='1 day')) %>% #添加未测量日期
group_by(Gas, Hybrid, Nrate, Plotnum) %>%
mutate(
# Check if there are any non-missing values of Flux
has_non_missing = any(!is.na(Flux)),
# If there are, apply na.approx(), otherwise use the original values of Flux
new = ifelse(has_non_missing, na.approx(Flux), Flux)
)
This code adds a new variable 'has_non_missing', which checks if there are any non-missing values of 'Flux' for each group of observations. It then uses 'ifelse()' to apply 'na.approx()' only if 'has_non_missing' is 'TRUE', and otherwise uses the original values of 'Flux'. This should prevent the error message related to the size of 'new'.
原文地址: https://www.cveoy.top/t/topic/l2w2 著作权归作者所有。请勿转载和采集!