【问题标题】:separate a column by a string [special case where the string is not always present]用字符串分隔一列[字符串并不总是存在的特殊情况]
【发布时间】:2021-06-01 15:16:34
【问题描述】:

我有一个看起来像这样的数据框

col1 <- c("test-1", "test-2","test")
col2 <- c(1,2,3)
df <- data.frame(col1,col2)

我想要单独的 col1,我的数据看起来像这样

check1 check2 col2 
test      1    1
test      2    2 
test     NA    3

这样的功能是行不通的

separate(df, col1, c("check1,check2"),"-")

知道为什么吗?

【问题讨论】:

  • 试试separate(df, col1, c("check1", "check2"),"[-]")

标签: r dplyr tidyverse tidyr


【解决方案1】:

在缺失值的情况下使用fill = 'right' 填充NA,并防止显示任何警告

col1 <- c("test-1", "test-2","test")
col2 <- c(1,2,3)
df <- data.frame(col1,col2)
library(tidyverse)
df %>% separate(col1, into = c('checkA', 'checkB'), sep = '-', fill = 'right')
#>   checkA checkB col2
#> 1   test      1    1
#> 2   test      2    2
#> 3   test   <NA>    3

reprex package (v2.0.0) 于 2021-06-01 创建

【讨论】:

    【解决方案2】:

    关于 OP 的问题,不是创建列名向量,而是存在语法问题,即 c("check1,check2") 是单个元素,应该是 c("check1","check2")

    separate(df, col1, c("check1","check2"),"-")
    

    【讨论】:

      猜你喜欢
      • 2021-07-23
      • 1970-01-01
      • 2013-05-25
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 2020-02-24
      • 1970-01-01
      • 2019-11-03
      相关资源
      最近更新 更多