我有以下数据框(tibble):
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
中的值排在四位,即始终位于foo, bar, qux, gop
:
> 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
答案 0 :(得分: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