编辑:该问题被标记为重复。但事实并非如此。本题不仅涉及将单个列拆分为多个列,因为我的单独代码可以工作。我提出的主要问题是当行字符串具有不同长度的列输出时拆分列。
我试图将这个:
data <- c("Place1-Place2-Place2-Place4-Place2-Place3-Place5",
"Place7-Place7-Place7-Place7-Place7-Place7-Place7-Place7",
"Place1-Place1-Place1-Place1-Place3-Place5",
"Place1-Place4-Place2-Place3-Place3-Place5-Place5",
"Place6-Place6",
"Place1-Place2-Place3-Place4")
转化为:
X1 X2 X3 X4 X5 X6 X7 X8
1 Place1 Place2 Place2 Place4 Place2 Place3 Place5
2 Place7 Place7 Place7 Place7 Place7 Place7 Place7 Place7
3 Place1 Place1 Place1 Place1 Place3 Place5
4 Place1 Place4 Place2 Place3 Place3 Place5 Place5
5 Place6 Place6
6 Place1 Place2 Place3 Place4
我尝试使用tidyr的separate函数,代码如下:
library(data.table)
data <- as.data.table(data)
data_table <- tidyr::separate(data,
data,
sep="-",
into = strsplit(data$data, "-"),
fill = "right")
很遗憾,我遇到了这个错误:
Warning message:
Too many values at 3 locations: 1, 2, 4
我需要做哪些改变才能使它工作?