根据存在的数据帧行分配分组变量R

时间:2018-07-30 17:32:35

标签: r dplyr gsub

我在R中有一个这样的列表:

cat1  
cat7  
cat10  
cat4  
frog  
dino11  
dino12  
dino15  
rabbit  

我需要制作一个新的数据框,如下所示:

cat1 frog  
cat7 frog  
cat10 frog  
cat4 frog  
dino11 rabbit  
dino12 rabbit  
dino15 rabbit

想法?谢谢!

3 个答案:

答案 0 :(得分:2)

我们根据'v1'中数字的不出现情况创建分组变量,以lag,创建一个新列'v2'作为'v1'的last元素,删除每个组的last行和感兴趣的select

library(tidyverse)
df %>%
  group_by(grp = lag(cumsum(grepl("^[^0-9]+$", v1)), default = 0)) %>% 
  mutate(v2 = last(v1)) %>% 
  slice(-n()) %>%
  ungroup %>%
  select(-grp)
# A tibble: 7 x 2
#  v1     v2    
#  <chr>  <chr> 
#1 cat1   frog  
#2 cat7   frog  
#3 cat10  frog  
#4 cat4   frog  
#5 dino11 rabbit
#6 dino12 rabbit
#7 dino15 rabbit

数据

df <- structure(list(v1 = c("cat1", "cat7", "cat10", "cat4", "frog", 
"dino11", "dino12", "dino15", "rabbit")), .Names = "v1",
 class = "data.frame", row.names = c(NA, -9L))

答案 1 :(得分:2)

类似于@akrun的答案,但带有data.table:

library(data.table)
setDT(df)

df[, .(
  anum = v1[-.N], 
  a = v1[.N]
), by=.(g = cumsum(!(shift(v1) %like% "\\d")))]

   g   anum      a
1: 1   cat1   frog
2: 1   cat7   frog
3: 1  cat10   frog
4: 1   cat4   frog
5: 2 dino11 rabbit
6: 2 dino12 rabbit
7: 2 dino15 rabbit

答案 2 :(得分:2)

仅对于基数R,您可以使用greplrle来实现。

where <- grepl("[[:digit:]]", x)
r <- rle(where)
A <- x[where]
B <- rep.int(x[!where], times = r$lengths[r$values])

data.frame(A, B)
#       A      B
#1   cat1   frog
#2   cat7   frog
#3  cat10   frog
#4   cat4   frog
#5 dino11 rabbit
#6 dino12 rabbit
#7 dino15 rabbit

数据。

x <- scan(what = character(), text = "
cat1  
cat7  
cat10  
cat4  
frog  
dino11  
dino12  
dino15  
rabbit  
")