R:用逗号将变量列拆分为多个(非平衡)列

时间:2015-07-23 02:56:41

标签: r split

我有一个包含25个变量和超过200万个观测值的数据集。我的一个变量是我想要拆分的几个不同“类别”的组合,每列显示1个类别(类似于stata中的拆分)。例如:

# Name      Age     Number               Events                      First 
# Karen      24        8         Triathlon/IM,Marathon,10k,5k         0
# Kurt       39        2         Half-Marathon,10k                    0 
# Leah       18        0                                              1

我希望它看起来像:

# Name   Age  Number Events_1        Event_2      Events_3     Events_4      First
# Karen   24    8     Triathlon/IM    Marathon       10k         5k             0
# Kurt    39    2     Half-Marathon   10k            NA          NA             0 
# Leah    18    0     NA              NA             NA          NA             1

我查看了stackoverflow,但没有发现任何有效的东西(一切都给我一些错误)。任何建议将不胜感激。

注意:可能不重要,但1人的最大类别数是19,因此我需要创建Event_1:Event_19

注释:以前的堆栈溢出建议使用单独的函数,但是此函数似乎不适用于我的数据集。当我输入函数时程序运行但是当它完成时没有任何改变,没有输出,也没有错误代码。当我尝试使用其他线程中提出的其他建议时,我收到了错误消息。但是,我终于通过使用cSplit功能得到了它。谢谢你的帮助!

1 个答案:

答案 0 :(得分:9)

来自Ananda的splitstackshape包裹:

cSplit(df, "Events", sep=",")
#    Name Age Number First      Events_1 Events_2 Events_3 Events_4
#1: Karen  24      8     0  Triathlon/IM Marathon      10k       5k
#2:  Kurt  39      2     0 Half-Marathon      10k       NA       NA
#3: Leah   18      0     1            NA       NA       NA       NA

tidyr

separate(df, 'Events', paste("Events", 1:4, sep="_"), sep=",", extra="drop")
#   Name Age Number               Events_1 Events_2 Events_3 Events_4 First
#1 Karen  24      8           Triathlon/IM Marathon      10k       5k     0
#2  Kurt  39      2          Half-Marathon      10k     <NA>     <NA>     0
#3 Leah   18      0                     NA     <NA>     <NA>     <NA>     1

使用data.table包:

setDT(df)[,paste0("Events_", 1:4) := tstrsplit(Events, ",")][,-"Events", with=F]
#    Name Age Number First               Events_1 Events_2 Events_3 Events_4
#1: Karen  24      8     0           Triathlon/IM Marathon      10k       5k
#2:  Kurt  39      2     0          Half-Marathon      10k       NA       NA
#3: Leah   18      0     1                     NA       NA       NA       NA

数据

df <- structure(list(Name = structure(1:3, .Label = c("Karen", "Kurt", 
"Leah "), class = "factor"), Age = c(24L, 39L, 18L), Number = c(8L, 
2L, 0L), Events = structure(c(3L, 2L, 1L), .Label = c("               NA", 
"         Half-Marathon,10k", "     Triathlon/IM,Marathon,10k,5k"
), class = "factor"), First = c(0L, 0L, 1L)), .Names = c("Name", 
"Age", "Number", "Events", "First"), class = "data.frame", row.names = c(NA, 
-3L))