-1

我有一个包含 10 列和 100,000 行的数据集。我有一个包含文本的列(我们将其命名为“column_A”),用逗号分隔:“motor, student, type_C”等。

我想拆分此列并将每个元素作为列的名称:因此它会将列“motor”、“student”、“type_C”添加到我的数据集中,以便用其他值填充这些新列。

实际上我已经拆分了角色,但我不知道如何将这些作为新列

strsplit(as.character(trimws(data$column_A)),",")

感谢您的帮助!

4

2 回答 2

0

这是否有效:

> dt <- data.frame(col_A = c("motor, student, type_C", "motor, student, type_B","motor, student, type_A"), stringsAsFactors = F)
> dt
                   col_A
1 motor, student, type_C
2 motor, student, type_B
3 motor, student, type_A
> dt %>% extract(col = col_A, into = c('C1','C2','C3'), regex = '(.*),\\s(.*),\\s(.*)')
     C1      C2     C3
1 motor student type_C
2 motor student type_B
3 motor student type_A
于 2020-10-20T09:57:22.113 回答
0

你可以试试这个:

library("tidyr")
data %>%
  separate(column_A, c("col1", "col2", "col3"), ",")

stringr包装:

library("stringr")    
str_split_fixed(data$column_A, ",", 3)

但我个人更喜欢选项一。

让我知道它是否有效。

于 2020-10-20T09:57:52.597 回答