我想根据Y
或data.table
将以下/
的{{1}}列拆分为两列。
-
必需
所需的结果是
df1 <-
structure(list(Y = c("1", "2", "3", "4", "5", "6/7", "8-10")),
.Names = "Y", row.names = c(NA, -7L)
, class = "data.frame"
)
library(data.table)
dt1 <- data.table(df1)
dt1[ , c("Y1", "Y2") := tstrsplit(Y, "/", fixed = TRUE)]
dt1
Y Y1 Y2
1: 1 1 NA
2: 2 2 NA
3: 3 3 NA
4: 4 4 NA
5: 5 5 NA
6: 6/7 6 7
7: 8-10 8-10 NA
我该怎么做?
答案 0 :(得分:3)
您可以选择第一个数字,即
library(data.table)
dt1[, Y1 := as.integer(gsub('[[:punct:]].*', '', Y))]
dt1
# Y Y1
#1: 1 1
#2: 2 2
#3: 3 3
#4: 4 4
#5: 5 5
#6: 6/7 6
#7: 8-10 8