根据数据框值将列拆分为两个

时间:2021-03-08 15:17:25

标签: r dplyr

我有一个像这样的数据框:

library(tidyverse)

tib <- tibble(Dis = c("One", "One", "Two", "Three", "Three"),
             Spray = c("F1", "F1", "F2", "other", "nj"),
             freq= c(80, 20, 1.34, 15.3, 20.2),
             Nom = c("A", "B", "C", "C", "D") )

我有一个数据框:

f <- c("F1", "F2", "F3", "F4", "F5", "F6", "F7")
s <- c("other", "nj", "na", "ker", "dsf", "dsf", "rth")

fs <- data.frame(f, s)

如您所见,数据框包含 Dis 和 Spray 列的值。每一个都对应另一个。

我想根据数据框将Spray列拆分为两列。

所以,我想要结果:

Dis   Spray  freq  Nom    f     s 
<chr> <chr> <dbl> <chr> <chr> <chr>
1 One   F1    80    A    F1    other
2 One   F1    20    B    F1    other
3 Two   F2    1.34  C    F2    nj
4 Three other 15.3  C    F1    other
5 Three nj    20.2  D    F2    other

一般,我已经创建了 f 和 s 的数据框,将其用作具有相应值的列表。此数据帧的大小与初始 tib 数据帧的大小会有所不同!

2 个答案:

答案 0 :(得分:1)

我没有看到拆分列的方法,但您可以使用 left_join()mutate() 的组合来实现所需的输出。

library(tidyverse)

tib %>% 
    left_join(fs, by = c("Spray" = "s"))
#> # A tibble: 5 x 5
#>   Dis   Spray  freq Nom   f    
#>   <chr> <chr> <dbl> <chr> <chr>
#> 1 One   F1    80    A     <NA> 
#> 2 One   F1    20    B     <NA> 
#> 3 Two   F2     1.34 C     <NA> 
#> 4 Three other 15.3  C     F1   
#> 5 Three nj    20.2  D     F2
tib %>% 
    left_join(fs, by = c("Spray" = "s")) %>% 
    left_join(fs, by = c("Spray" = "f"))
#> # A tibble: 5 x 6
#>   Dis   Spray  freq Nom   f     s    
#>   <chr> <chr> <dbl> <chr> <chr> <chr>
#> 1 One   F1    80    A     <NA>  other
#> 2 One   F1    20    B     <NA>  other
#> 3 Two   F2     1.34 C     <NA>  nj   
#> 4 Three other 15.3  C     F1    <NA> 
#> 5 Three nj    20.2  D     F2    <NA>
# Desired output
tib %>% 
    left_join(fs, by = c("Spray" = "s")) %>% 
    left_join(fs, by = c("Spray" = "f")) %>% 
    mutate(f = if_else(is.na(f), Spray, f), 
           s = if_else(is.na(s), Spray, s))
#> # A tibble: 5 x 6
#>   Dis   Spray  freq Nom   f     s    
#>   <chr> <chr> <dbl> <chr> <chr> <chr>
#> 1 One   F1    80    A     F1    other
#> 2 One   F1    20    B     F1    other
#> 3 Two   F2     1.34 C     F2    nj   
#> 4 Three other 15.3  C     F1    other
#> 5 Three nj    20.2  D     F2    nj

reprex package (v0.3.0) 于 2021 年 3 月 8 日创建

答案 1 :(得分:0)

有这样的吗? (我认为您的预期输出在第 5 行,否则我不知道您在寻找什么:p)

tib$f <- NA
tib$s <- NA
c <- 1

for (i in tib$Spray){
  if (i %in% f){
    tib$f[c] <- i
    is <- match(i,f)
    tib$s[c] <- s[is]
    c <- c + 1
  }
  else{
    is <- match(i,s)
    tib$f[c] <- f[is]
    tib$s[c] <- i
    c <- c + 1
  }
}