r - 使用 "."分隔符 R 将一列拆分为 2 列

标签 r tidyr

我有以下数据集:

the_data <- data.frame(the_col = "a.1","b.2","c.3","d.4")

我试着把它分成两列。这似乎是一个重复的问题,但让它与众不同的是我想要的分隔符(点)。我试过:

the_data %>% separate(the_col, into = c("alfa","beta"), sep = ".") 

但是我收到了一个警告,而不是我想要的:

 alfa beta X.b.2. X.c.3. X.d.4.
1              b.2    c.3    d.4

我想要的是:

alfa   beta
a      1
b      2 
c      3
d      4

你能帮帮我吗?谢谢。

最佳答案

我们可以获取long格式的数据,然后使用separate

library(dplyr)
library(tidyr)

pivot_longer(the_data, cols = everything()) %>%
  separate(value, into = c('alpha', 'beta'), sep = "\\.") %>%
  select(-name)

# A tibble: 4 x 2
#  alpha beta 
#  <chr> <chr>
#1 a     1    
#2 b     2    
#3 c     3    
#4 d     4    

使用 base R,我们可以拆分 "." 上的未列出的字符串,将其转换为两列数据框并为其添加名称。

setNames(do.call(rbind.data.frame, strsplit(unlist(the_data), '\\.')), 
         c('alpha', 'beta'))

关于r - 使用 "."分隔符 R 将一列拆分为 2 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61787280/

相关文章:

r - 如何使用 R 中的 rms 包进行负二项式回归?

R Quantreg : Singularity with categorical survey data

r - 将列表列分成 R 中的列

r - 扩展数据框使其行数与原始行中两列的范围一样多

r - 使用具有不确定数量的列的 replace_na()

r - tidyr spread函数如何将变量作为选择列

r - 为什么我们在 R 中的 model.matrix 函数中提到 -1 ?是为了一种热编码还是有其他原因?

r - 在 R 中的泰勒图中添加偏差

识别 R 中的日期时间格式

r - 按列名中的模式融化数据帧