R 使用某些行作为分组新列中的值(从excel导入的数据)
我有关于德国PM10浓度的数据。可在此[链接]() 在excel中,大致如下所示: 这里的问题是,对于16个州中的每一个州,都有一行“连接”,直到下一行出现这种情况,都有测量PM10浓度的独立监测站。我现在要做的是为每个州创建一个新列,每个州都为每个度量指定州的名称 老实说,我不知道如何在R中做到这一点。我想可能会有一些工作在伪代码中,比如R 使用某些行作为分组新列中的值(从excel导入的数据),r,excel,tidyverse,R,Excel,Tidyverse,我有关于德国PM10浓度的数据。可在此[链接]() 在excel中,大致如下所示: 这里的问题是,对于16个州中的每一个州,都有一行“连接”,直到下一行出现这种情况,都有测量PM10浓度的独立监测站。我现在要做的是为每个州创建一个新列,每个州都为每个度量指定州的名称 老实说,我不知道如何在R中做到这一点。我想可能会有一些工作在伪代码中,比如 state = None for each row: if (NA in Statiocode): state = Name else:
state = None
for each row:
if (NA in Statiocode):
state = Name
else:
new_col = state
这看起来像是某种正确的方法吗?我希望以下内容能有所帮助
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))
data%select(`Name/Messnetz`)
索引这个代码就可以了
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
库(readxl)
数据%
填充(状态)%%>%过滤器(!is.na(StationCode))%%>%选择(状态,所有内容())
数据
#A tibble:376x7
州站代码`Name/Messnetz`Stationsumgebung`artderstation``Jahresmittelwert\~`zahldertageswerte~
1巴登-Wü~DEBW029 Aalen vorstädtisches Ge~腹地14 0
2巴登-Wü~DEBW076巴登-巴登-沃斯特ädtisches Ge~腹地12 0
3巴登-Wü~DEBW042伯恩豪森-沃斯塔德教堂16 2
4巴登-Wü~DEBW046 Biberach vorstädtisches Ge~Hintergrund 14 0
5巴登-Wü~DEBW004埃肯斯坦林德里希斯塔德纳暗示15 0
6巴登-Wü~DEBW220埃斯林根地堑布伦~städtisches Gebiet Verkehr 23 16
7巴登-Wü~DEBW084弗赖堡städtisches Gebiet Hintergrund 13 2
8巴登-Wü~DEBW122弗赖堡-施瓦茨瓦尔-圣比埃特-维尔凯尔15 3
9巴登-Wü~DEBW038弗里德里希沙芬圣德提斯教堂暗示14 1
10巴登-Wü~DEBW112 Gärtringen vorstädtisches Ge~Hintergrund 13 1
# ... 还有366行