将数据框的行分成多行
Divide lines of a dataframe in multiple lines
假设您有一个带有 ID x 和字符串 y 的数据框:
x y
1 a-b-c
2 d-e
我想要以下数据框:
x y
1 a
1 b
1 c
2 d
2 e
尝试使用 tidyr
中的 separate_rows
:
library(tidyr)
dff <- structure(list(x = 1:2,
y = structure(1:2, .Label = c("a-b-c","d-e"),
class = "factor")), .Names = c("x", "y"),
class = "data.frame", row.names = c(NA,-2L))
dff %>%
separate_rows(y)
# x y
#1 1 a
#2 1 b
#3 1 c
#4 2 d
#5 2 e
希望对您有所帮助。
我们可以试试
library(splitstackshape)
cSplit(dff, "y", "-", "long")
# x y
#1: 1 a
#2: 1 b
#3: 1 c
#4: 2 d
#5: 2 e
假设您有一个带有 ID x 和字符串 y 的数据框:
x y
1 a-b-c
2 d-e
我想要以下数据框:
x y
1 a
1 b
1 c
2 d
2 e
尝试使用 tidyr
中的 separate_rows
:
library(tidyr)
dff <- structure(list(x = 1:2,
y = structure(1:2, .Label = c("a-b-c","d-e"),
class = "factor")), .Names = c("x", "y"),
class = "data.frame", row.names = c(NA,-2L))
dff %>%
separate_rows(y)
# x y
#1 1 a
#2 1 b
#3 1 c
#4 2 d
#5 2 e
希望对您有所帮助。
我们可以试试
library(splitstackshape)
cSplit(dff, "y", "-", "long")
# x y
#1: 1 a
#2: 1 b
#3: 1 c
#4: 2 d
#5: 2 e