2017-04-14 60 views
0

重命名與塊模式中行我有以下的數據幀(tibble):在foo, bar, qux, gop如何使用dplyr

library(tidyverse) 
lines<-" 
A,foo,9394981 
B,bar,6826405 
C,qux,1074885 
D,gop,1493691 
A,foo,100 
B,bar,200 
C,qux,300 
D,gop,400 
" 
con <- textConnection(lines) 
dat <- read.csv(con,header=FALSE) 
close(con) 
dat <- as.tibble(dat) 
dat 

V2的值來以四個塊,即始終:

> dat 
# A tibble: 8 × 3 
     V1  V2  V3 
    <fctr> <fctr> <dbl> 
1  A foo 9394981 
2  B bar 6826405 
3  C qux 1074885 
4  D gop 1493691 
5  A foo  100 
6  B bar  200 
7  C qux  300 
8  D gop  400 

我怎樣才能在V2重命名該行,以便它變成這樣:

A foo.w 9394981 
    B bar.x 6826405 
    C qux.y 1074885 
    D gop.z 1493691 
    A foo.w  100 
    B bar.x  200 
    C qux.y  300 
    D gop.z  400 

回答

2
# If V2 is in the order of foo, bar, qux, gop 
dat %>% mutate(V2=paste(V2, c("w", "x", "y", "z"), sep=".")) 
# A tibble: 8 × 3 
     V1 V2  V3 
    <fctr> <chr> <dbl> 
1  A foo.w 9394981 
2  B bar.x 6826405 
3  C qux.y 1074885 
4  D gop.z 1493691 
5  A foo.w  100 
6  B bar.x  200 
7  C qux.y  300 
8  D gop.z  400 

# If not, create a lookup 
lookup <- c("foo"="foo.w", "bar"="bar.x", "qux"="qux.y", "gop"="gop.z") 
dat %>% mutate(V2=lookup[as.character(V2)]) 
# A tibble: 8 × 3 
     V1 V2  V3 
    <fctr> <chr> <dbl> 
1  A foo.w 9394981 
2  B bar.x 6826405 
3  C qux.y 1074885 
4  D gop.z 1493691 
5  A foo.w  100 
6  B bar.x  200 
7  C qux.y  300 
8  D gop.z  400