根据单词或数字将一列分成多列

时间:2019-11-26 10:06:57

标签: r dplyr

我希望将当前数据帧中的列扩展为所需数据帧中的两列。当前版本之所以这样,是因为它已被废弃并且无法更改。我曾考虑过使用dplyr或正则表达式来将单词与时间分开,但是却不知道该怎么做。

我的真实数据框具有真实的电影院名称(以大写字母开头的一个或两个单词)

我当前的数据框列的类型为“整数”

current <- data.frame(times = c("cinema1", "10:30", "12:30", "cinema2", "9:30", 
                              "16,30", "cinema3", "17:30"), stringsAsFactors = FALSE)
current$times <- as.integer(current$times)


desired <- data.frame(cinema = c("cinema1", "cinema1", "cinema2", "cinema2", "cinema3"), 
                     times = c("10:30", "12:30", "9:30", "16,30", "17:30"), stringsAsFactors = FALSE)


谢谢

3 个答案:

答案 0 :(得分:3)

使用dplyrtidyr::fill,我们可以首先将replacetimes以外的"cinema" NA。然后填写缺少的值,并在"cinema"中用times删除行。

library(dplyr)

current %>%
  mutate(cinema = replace(times, !grepl("^cinema", times), NA)) %>%
  tidyr::fill(cinema) %>%
  filter(!grepl("^cinema", times))

#  times  cinema
#1 10:30 cinema1
#2 12:30 cinema1
#3  9:30 cinema2
#4 16:30 cinema2
#5 17:30 cinema3

数据

current <- data.frame(times = c("cinema1", "10:30", "12:30", "cinema2", "9:30", 
                        "16:30", "cinema3", "17:30"), stringsAsFactors = FALSE)

答案 1 :(得分:0)

使用dplyr的另一种方法可能是:

current %>%
 group_by(grp = cumsum(grepl("cinema", times, fixed = TRUE))) %>%
 mutate(cinema = first(times)) %>%
 filter(row_number() != 1) %>%
 ungroup() %>%
 select(-grp)

  times cinema 
  <chr> <chr>  
1 10:30 cinema1
2 12:30 cinema1
3 9:30  cinema2
4 16,30 cinema2
5 17:30 cinema3

答案 2 :(得分:0)

我们可以将stack中的greplbase R一起使用

i1 <- grepl('cinema', current$times)
stack(setNames(split(current$times[!i1], cumsum(i1)[!i1]), current$times[i1]))
#  values     ind
#1  10:30 cinema1
#2  12:30 cinema1
#3   9:30 cinema2
#4  16,30 cinema2
#5  17:30 cinema3