【问题标题】:calculate the mean for a column of a dataframe in R ignoring NA and 0 values计算 R 中数据框列的平均值,忽略 NA 和 0 值
【发布时间】:2021-04-16 20:10:12
【问题描述】:

我在 r 中有一个数据框,它有一个 date_time 列(每 10 分钟一次观察)和另一列 lux ..我想计算整个列的平均 lux,忽略 NA 和 0 值。

我还想计算平均每日勒克斯..

我该怎么做?

【问题讨论】:

  • 第二部分我使用 meandailylux

标签: r dataframe mean


【解决方案1】:

如果没有示例数据集,我只能通过提供来自另一个数据集的工作示例来提供帮助。复制粘贴以下内容,并将文件命名为:daily-min-temperatures.txt

"Date","Temp"
"1981-01-10",20.0
"1981-01-11",0
"1981-01-12",13.3
"1981-01-13",NA
"1981-01-14",21.5
"1981-02-09",25.0
"1981-02-10",0
"1981-02-11",13.7
"1981-02-12",NA
"1981-03-08",16.3
"1981-03-09",16.1
"1981-03-10",11.8
"1981-03-11",12.2
"1981-03-12",0
"1981-03-13",0
"1981-03-14",NA
"1981-03-15",10.6
"1981-03-16",11.7

数据框与您的相似:不是每 10 分钟记录一次,而是每天的温度记录一些 NA 和 0。

这里是工作示例。通过一些调整,您可以根据自己的情况进行调整。

daily_min_temperatures <- read.csv("daily-min-temperatures.txt") #load sample dataframe
daily_min_temperatures$Date <- as.Date(daily_min_temperatures$Date) #format Date field

str(daily_min_temperatures) #view the structure of the loaded dataframe
summary(daily_min_temperatures) #view the summary of the loaded dataframe

library(tidyverse) #load the tidyverse library to get some nice to have tools :)
#part 1: average temp for full dataframe
na.omit(daily_min_temperatures) %>% #remove the NAs entries from the dataframe with the na.omit statement
filter(Temp != 0) %>% #remove the 0s entries from the dataframe with the filter statement
summarise(mean = mean(Temp)) #calculate the Temp mean

#part 2: average temp for monthly dataframe
na.omit(daily_min_temperatures) %>% #remove the NAs entries from the dataframe with the na.omit statement
filter(Temp != 0) %>% #remove the 0s entries from the dataframe with the filter statement
group_by(Grouped_Date = format(Date, format="%m/%Y")) %>% #Group by month year
summarise(mean = mean(Temp)) #calculate the Temp mean for each group

【讨论】:

    猜你喜欢
    • 2020-12-19
    • 2020-09-01
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2022-01-12
    • 2020-03-27
    • 2017-08-28
    • 1970-01-01
    相关资源
    最近更新 更多