【问题标题】:split column of list of dataframes拆分数据框列表的列
【发布时间】:2017-05-28 09:10:02
【问题描述】:

我有一个数据框列表。每个数据框只有一列,数据分隔为“\t”。不同数据框的列名称不同。我想拆分列并为新列提供名称。

list.df <- c(df1,df2,df3....df1000)
df1
$`000004.ame`
[1] 0.0\t0.00\t12.1\t1.0\t14.01\t1       2.0\t0.00\t13.9\t-0.2\t14.02\t1     
[3] 4.0\t-0.00\t13.2\t0.2\t14.01\t1      6.0\t0.00\t12.8\t0.0\t14.02\t1      
[5] 8.0\t0.00\t13.7\t0.0\t14.02\t1

other data frames are similar with different column names

我为一个数据框获得了它,但我想应用于数据框列表

 colnames(X) <- "text"
 library(splitstackshape)
 X <- cSplit(as.data.frame(X),"text","\t")
 colnames(X) <- c("T","I")

如何将其应用于数据框列表? 请指导我这方面

【问题讨论】:

  • 请分享您的数据的可重现示例
  • 我编辑了我的问题
  • 使用lapply 遍历列表,类似于lapply(list.df, function(i) {d1 &lt;- data.frame(text = i); cSplit(d1, 'text', '\t')})(未经测试)
  • 谢谢。它正在工作

标签: r


【解决方案1】:
library(stringr)

# Creating similiar dfs

vec1 <- c("0.0\t0.00\t12.1\t1.0\t14.01\t1","0.0\t0.00\t12.1\t1.0\t14.01\t1" 
,"0.0\t0.00\t12.1\t1.0\t14.01\t1","0.0\t0.00\t12.1\t1.0\t14.01\t1")
df1 <- as.data.frame(vec1, stringsAsFactors = FALSE)

df2 <- df1

list.df <- c(df1,df2)

# Looping over this list with lapply
# Using stringrs str_split instead of splitstackshape


 list.splitted.dfs <- lapply(list.df, function(x) unlist(str_split(x[1], 
 "\t")))

 # Output from above is a list, need to bind it together
 new <- as.data.frame(do.call(rbind, list.splitted.dfs))
 > newdf
 V1   V2   V3  V4    V5    V6
 1 0.0 0.00 12.1 1.0 14.01  1
 2 0.0 0.00 12.1 1.0 14.01  1  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-22
    • 2018-03-03
    • 1970-01-01
    • 2019-01-11
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多