1

我有关于德国 PM10 浓度的数据。它可以在这个 [链接] ( https://www.umweltbundesamt.de/sites/default/files/medien/4640/dokumente/pm10_2019_0.xlsx )下载

在 excel 中,它或多或少看起来像这样:

在此处输入图像描述

这里的问题是,对于 16 个州中的每一个州,都有“连接”一行,直到下一行,都有单独的站点测量 PM10 浓度。我现在想做的是为每个状态创建一个新列,每个状态都将状态名称分配给每个测量值。

老实说,我不知道如何在 R 中做到这一点。我想在伪代码中可能会有一些解决方法,比如

state = None
for each row: 
  if (NA in Statiocode):
    state = Name
  else:
    new_col = state

这看起来像是某种正确的方法吗?

4

2 回答 2

1

我希望以下内容有所帮助

data <- read_excel("pm10_2019_0.xlsx", skip = 46)
names <- data %>% filter(is.na(Stationscode)) %>% select(`Name / Messnetz`)
index <- which(is.na(data$Stationscode))

for(i in 1:nrow(data)){
  
  data[i,"City"] <- cut(i, breaks = c(index, nrow(data)), labels = names$`Name / Messnetz`)
  
}
data <- data %>% filter(!is.na(Stationscode))
于 2020-12-24T15:13:12.983 回答
1

很简单,这段代码就可以了

library(readxl)
data <- read_excel("pm10_2019_0.xlsx", skip = 46)

library(tidyverse)

data <- data %>% mutate(State = ifelse(is.na(Stationscode), `Name / Messnetz`, NA)) %>%
  fill(State) %>% filter(!is.na(Stationscode)) %>% select(State, everything())

data
# A tibble: 376 x 7
   State     Stationscode `Name / Messnetz`    Stationsumgebung   `Art der Station` `Jahresmittelwert \~ `Zahl der Tageswerte ~
   <chr>     <chr>        <chr>                <chr>              <chr>                            <dbl>                  <dbl>
 1 Baden-Wü~ DEBW029      Aalen                vorstädtisches Ge~ Hintergrund                         14                      0
 2 Baden-Wü~ DEBW076      Baden-Baden          vorstädtisches Ge~ Hintergrund                         12                      0
 3 Baden-Wü~ DEBW042      Bernhausen           vorstädtisches Ge~ Hintergrund                         16                      2
 4 Baden-Wü~ DEBW046      Biberach             vorstädtisches Ge~ Hintergrund                         14                      0
 5 Baden-Wü~ DEBW004      Eggenstein           ländlich stadtnah  Hintergrund                         15                      0
 6 Baden-Wü~ DEBW220      Esslingen Grabbrunn~ städtisches Gebiet Verkehr                             23                     16
 7 Baden-Wü~ DEBW084      Freiburg             städtisches Gebiet Hintergrund                         13                      2
 8 Baden-Wü~ DEBW122      Freiburg Schwarzwal~ städtisches Gebiet Verkehr                             15                      3
 9 Baden-Wü~ DEBW038      Friedrichshafen      städtisches Gebiet Hintergrund                         14                      1
10 Baden-Wü~ DEBW112      Gärtringen           vorstädtisches Ge~ Hintergrund                         13                      1
# ... with 366 more rows
于 2020-12-24T15:43:40.693 回答