如何使用空格将一列拆分为两列
我有以下输入数据框。我需要根据它们之间的空格将这个 df 分成两列 [l,r] 。问题是大部分库都不存在于 compile Env 中。有没有不使用“dplyr”或“tidyr”的其他方法
输入
df
val
1 5 5
2 2 7
3 8 10
4 10 20
5 4 5
输出
df
l r
1 5 5
2 2 7
3 8 10
4 10 20
5 4 5
回答
base R通过使用read.table读取列“val”更容易,它会自动在空白处拆分列。只需指定列名(如果我们需要),否则它会创建默认名称。优点是如果我们使用它会自动更改而不是手动更改strsplit
read.table(text = df$val, header = FALSE, col.names = c('l', 'r'))
-输出
l r
1 5 5
2 2 7
3 8 10
4 10 20
5 4 5
数据
df <- structure(list(val = c("5 5", "2 7", "8 10", "10 20", "4 5")),
class = "data.frame", row.names = c(NA, -5L))
回答
一个基本的 R 选项 scan
> matrix(scan(text = paste0(df$val)), nrow(df), byrow = TRUE)
Read 10 items
[,1] [,2]
[1,] 5 5
[2,] 2 7
[3,] 8 10
[4,] 10 20
[5,] 4 5
或(感谢@Onyambu 的评论)
> list2DF(scan(text = df$val, what = list(as.numeric(), as.numeric())))
Read 5 records
1 5 5
2 2 7
3 8 10
4 10 20
5 4 5
一个data.table选项使用tstrsplit
> setDT(df)[, tstrsplit(val, " ", type.convert = TRUE)]
V1 V2
1: 5 5
2: 2 7
3: 8 10
4: 10 20
5: 4 5
- if you are using `scan` include the `what` argument thus you will not need to use as.matrix: `list2DF(scan(text=df$val, what=list(as.numeric(), as.numeric())))`