将基于模式的数据帧行拆分为新列

时间:2020-02-04 08:46:13

标签: r regex dataframe strsplit

我有一个看起来像这样的数据框

df

Country     Year  col3. col4. col5
USA2018      10    50    13   NA
UK 2018       4    12     6   NA
China       2018   15     4    1
Malta        NA    2018  25    8

我想用模式“ 2018”将“国家/地区”列的字符串拆分为将2018年合并到第一列的行,并转移到“年份”列以获取“年”为NA的行,并具有以下输出:

df

Country     Year  col3. col4. col5
USA         2018   10    50    13   
UK          2018   4    12     6   
China       2018   15    4    1
Malta       2018   25    8     NA

有什么建议吗?


编辑:此数据是PDF抓取的结果。Link to PDF,以及以下代码:

# install.packages("pdftools") 
# install.packages("readr") 
library(pdftools) 
library(readr) 


epi <- pdf_text("malaria_epi.pdf") 
epi_df <- epi %>% 
  read_lines() %>% 
  grep('^\\s{2}\\w', ., value = TRUE) %>% 
  paste(collapse = '\n') %>% read_fwf(fwf_empty(.)) 

1 个答案:

答案 0 :(得分:1)

这是一个解决方案。这有点棘手,但我认为它可以解决您的问题。 如果您连续遇到不适用,则此解决方案可能会出现问题,但我还没有找到更好的方法。

df <- read.table(header=TRUE, 
                 text="
Country     Year  col3. col4. col5
USA2018      10    50    13   NA
UK2018       4    12     6   NA
China       2018   15     4    1
Malta        NA    2018  25    8")

tmpN <- names(df) # save the colnames
df = cbind(df[,1],df) # duplicate the first column
df[,c(1,2)] <- lapply(df[,c(1,2)], as.character)

df[,1] = sub('[[:digit:]]+','',df[,1]) # remove date in first column
df[,2] = sub('[[:alpha:]]+','',df[,2]) # remove city in second column
df[df==''] <- NA # replace empty cells with NA

# push all NA to the right side
df2 = as.data.frame(t(apply(df,1, function(x) { return(c(x[!is.na(x)],x[is.na(x)]) )} )))
df2 <- df2[,!(colSums(is.na(df2))==nrow(df2))] # remove column full of NA

colnames(df2) <- tmpN # replace colnames
相关问题