【问题标题】:Split columns of a dataframe and re-combine them as one column without blanks拆分数据框的列并将它们重新组合为一列而没有空格
【发布时间】:2018-07-26 10:47:05
【问题描述】:

我有两个要根据“;”拆分的数据框,并将结果列重新组合成具有相应值的一列。

查看下面的示例。 df2 中的每个数字对应 df1 中的一个字符串("aaa" 111、"bbbb" 2222、"ccc" 333 等)

#The dataframes I have
df1 = c("aaa","bbbb;ccc","dd;eeee;ffff","gg") #1st dataframe
df2 = c("111","2222;333","44;5555;6666","77") #2nd dataframe
df = as.data.frame(cbind(df1,df2)) #combine df1 and df2

#The output I'm trying to achieve
df1_desired = c("aaa","bbbb","ccc","dd","eeee","ffff","gg")
df2_desired = c("111","2222","333","44","5555","6666","77")
df_desired = as.data.frame(cbind(df1_desired,df2_desired)) #this is the format I want

我尝试了以下,但它没有给我我需要的安排。

split_df1 = str_split_fixed(df$df1, ";", 3)
split_df2 = str_split_fixed(df$df2, ";", 3)
combined_output = cbind(split_df1 ,split_df2 )

非常感谢您的建议!

更新

@snoram 提供的这个解决方案非常适合我:

library(data.table)
setDT(df)
dfd <- df[, lapply(.SD, tstrsplit, ";"), by = seq_len(nrow(df))][, seq_len := NULL]
dfd

【问题讨论】:

标签: r dataframe split


【解决方案1】:
library(data.table)
setDT(df)
dfd <- df[, lapply(.SD, tstrsplit, ";"), by = seq_len(nrow(df))][, seq_len := NULL]
dfd
    df1  df2
1:  aaa  111
2: bbbb 2222
3:  ccc  333
4:   dd   44
5: eeee 5555
6: ffff 6666
7:   gg   77

受rar启发的Base R:

data.frame(lapply(lapply(df, strsplit, ";"), unlist))

【讨论】:

    【解决方案2】:
    > data.frame(cbind(unlist(strsplit(df1,";")),unlist(strsplit(df2,";"))))
        X1   X2
    1  aaa  111
    2 bbbb 2222
    3  ccc  333
    4   dd   44
    5 eeee 5555
    6 ffff 6666
    7   gg   77
    

    首先根据“;”拆分文本,然后取消列出,cbind两个结果并转换为数据框。

    【讨论】:

      猜你喜欢
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 2012-09-25
      • 2021-01-19
      • 2020-09-14
      • 2020-08-18
      相关资源
      最近更新 更多