用字符串分隔列[字符串并不总是存在的特殊情况]
separate a column by a string [special case where the string is not always present]
我有一个看起来像这样的数据框
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"),"-")
知道为什么吗?
使用 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
关于 OP 的问题,不是创建列名向量,而是语法问题,即 c("check1,check2")
是单个元素,应该是
c("check1","check2")
separate(df, col1, c("check1","check2"),"-")
我有一个看起来像这样的数据框
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"),"-")
知道为什么吗?
使用 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关于 OP 的问题,不是创建列名向量,而是语法问题,即 c("check1,check2")
是单个元素,应该是
c("check1","check2")
separate(df, col1, c("check1","check2"),"-")