我正在尝试根据Name列中元素的长度来复制数据帧中的行,例如,如果元素df $ Name [1]的长度为3,则我将重复行3次,但每个新行都会有一个新行Name列中的元素从df $ Name [1]的2nd和3rd元素派生。在R中有更简单的方法吗?
Dataframe looks like this
df=
Name c1 c2 c3
c("g7","g8","g9") 2016 82 5
g54 2016 81 1
g5 2016 81 4
g3 2016 82 4
c("g1","g2") 2015 79 1
g45 2016 82 1
Expected Result
df2=
Name c1 c2 c3
g7 2016 82 5
g8 2016 82 5
g9 2016 82 5
g54 2016 81 1
g5 2016 81 4
g3 2016 82 4
g1 2015 79 1
g2 2015 79 1
g45 2016 82 1
答案 0 :(得分:0)
您可以使用tidyr::unnest()
:
tidyr::unnest(df, Name)
# c1 c2 c3 Name
#1 2016 82 5 g7
#2 2016 82 5 g8
#3 2016 82 5 g9
#4 2016 81 1 g54
#5 2016 81 4 g5
#6 2016 82 4 g3
#7 2015 79 1 g1
#8 2015 79 1 g2
#9 2016 82 1 g45
df <-
structure(list(Name = list(c("g7", "g8", "g9"), "g54", "g5",
"g3", c("g1", "g2"), "g45"), c1 = c(2016L, 2016L, 2016L,
2016L, 2015L, 2016L), c2 = c(82L, 81L, 81L, 82L, 79L, 82L), c3 = c(5L,
1L, 4L, 4L, 1L, 1L)), row.names = c(NA, -6L), class = "data.frame")