简体   繁体   English

R - dplyr 中字符串的列

[英]R - column from string in dplyr

my dataframe look like this我的 dataframe 看起来像这样

x <-
  data.frame(
    id = c("123_1", "987_123")
  )

I'd like to create this result dataframe via dplyr mutate function.我想通过 dplyr 变异 function 创建这个结果 dataframe。 I just want to take first part before underscore sign and another one right after underscore sign.我只想在下划线符号之前参加第一部分,在下划线符号之后参加另一部分。

result <-
  data.frame(
    id = c("123_1", "987_123"),
    af = c("123", "987"),
    ad = c("1", "123")
  )

1) tidyverse Use separate like this: 1) tidyverse像这样separate使用:

library(dplyr)
library(tidyr)

x %>%
  separate(id, c("af", "ad"), remove = FALSE)
##        id  af  ad
## 1   123_1 123   1
## 2 987_123 987 123

2) Base R 2) 底座 R

2a) read.table Without any packages use read.table 2a) read.table没有任何包使用read.table

cbind(x, read.table(text = x$id, sep = "_", col.names = c("af", "ad"),
  colClasses = "character"))
##        id  af  ad
## 1   123_1 123   1
## 2 987_123 987 123

2b) sub or use sub : 2b) sub或使用sub

transform(x, af = sub("_.*", "", id), ad = sub(".*_", "", id))
##        id  af  ad
## 1   123_1 123   1
## 2 987_123 987 123

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM