表重组拆分R

时间:2018-08-06 08:43:04

标签: r dataframe

我有一个表格,其中有一个可变技术,其中包括“ AllRenewables”,“生物质”,“太阳能”,“海上风”,“陆上风”和“风”。

我希望将“所有可再生能源”分为“生物质”,“太阳能”,“离岸风”,“陆上风”,并且将“风”技术分为“离岸风”,“陆上”风”。

该表大致如下所示:

表格

 Year   Country   Technology       Changes
  2000   A       Solar             1
  2000   A       Wind              2
  2000   A       Onshore wind      2
  2000   A       All Renewables    3

重组后的外观如下:

表格

  Year   Country    Technology       Changes
  2000     A           Solar           1
  2000     A           Onshore wind    2
  2000     A           Offshore wind   2
  2000     A           Onshore wind    3
  2000     A           Biomass         3
  2000     A           Solar           3
  2000     A           Onshore wind    3
  2000     A           Offshore wind   3

如果有人能帮助我,我将非常感谢。 莎拉

2 个答案:

答案 0 :(得分:1)

您可以重命名因子水平并使用tidyr::separate_rows

lvls <- c(
    "Biomass, Solar, Offshore wind, Onshore wind",
    "Onshore wind",
    "Solar",
    "Offshore wind, Onshore wind")
levels(df$Technology) <- lvls;

library(tidyverse)
df %>% separate_rows(Technology, sep = ", ") %>%
    group_by_all() %>%
    slice(1) %>%
    ungroup() %>%
    arrange(Changes)
## A tibble: 7 x 4
#   Year Country Technology    Changes
#  <int> <fct>   <chr>           <int>
#1  2000 A       Solar               1
#2  2000 A       Offshore wind       2
#3  2000 A       Onshore wind        2
#4  2000 A       Biomass             3
#5  2000 A       Offshore wind       3
#6  2000 A       Onshore wind        3
#7  2000 A       Solar               3

说明:我们重新定义因子级别,以使"All Renewables"变成"Biomass, Solar, Offshore wind, Onshore wind",而"Wind"变成"Offshore wind, Onshore wind"。然后,我们使用tidyr::separate_rows将带有逗号的条目拆分为单独的行。剩下的就是删除重复项并重新排列行。


样本数据

df <- read.table(text =
    "Year  Country  Technology  Changes
2000  A  'Solar'  1
2000  A  'Wind'  2
2000  A  'Onshore wind'  2
2000  A  'All Renewables'  3", header = T)

答案 1 :(得分:0)

只是合并问题(与tidyverse):

# Your data:
df <- read.csv(textConnection("Y, A, B, C
2000,A,Solar,1
2000,A,Wind,2
2000,A,Onshore wind,2
2000,A,All Renewables,3"),stringsAsFactors=FALSE)
# Your synonyms: 
c <- read.csv(textConnection("B, D
All Renewables,Biomass
All Renewables,Solar
All Renewables,Offshore wind
All Renewables,Onshore wind
Wind,Offshore wind
Wind,Onshore wind"),stringsAsFactors=FALSE)

df %>% left_join(c,by="B") %>% mutate(B=coalesce(D,B)) %>% select(-D)
#     Y A              B C
#1 2000 A          Solar 1
#2 2000 A  Offshore wind 2
#3 2000 A   Onshore wind 2
#4 2000 A   Onshore wind 2
#5 2000 A        Biomass 3
#6 2000 A          Solar 3
#7 2000 A  Offshore wind 3
#8 2000 A   Onshore wind 3