导入多个数据框CSV - 列分隔

时间:2015-03-30 19:53:11

标签: r csv

我有一个csv文件,其中包含多个数据框,这些数据框全部由列分隔(因此4列数据,空列,4列数据等)。有没有一种很好的方法来读取文件并让R为每个连续的列集创建一个单独的df?然后我就可以在所有这些dfs中使用lapply。

感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

读入整个csv文件,然后使用lapply将每个四列数据帧分别捕获到一个列表中。然后使用rbind将所有数据帧堆叠到一个数据帧中。

dat = read.csv("YourFile.csv")

# Set this based on how many separate data frames are in your csv file
num.df = ncol(dat)/5  # Per @zx8754's comment

# This will tell the function the column numbers where
# each data frame starts
start.cols = seq(1, 1 + 5*(num.df-1), 5)

df.list = lapply(start.cols, function(x) {

  # Capture the next 4 columns
  df = dat[, x:(x+3)]

  # Use whatever names are appropriate here. This is just
  # to make sure all of the data frames have the same column names
  # so that rbind won't throw an error
  names(df) = c(paste0("col", 1:4))
  return(df)
})

# rbind all the data frames into a single data frame
df = do.call(rbind, df.list)

答案 1 :(得分:1)

您可以利用colClasses

示例数据:

  h1 h2 h3     h1.1 h2.1 h3.1     h1.2 h2.2 h3.2
1  1  6  3       1    8    8        1    5    2
2  2  1  1       6    5    8        1    3    1
3  3  2  6       1    2    3        1    2    5

然后你可以遍历你想要的数据帧数并读取文件:

ngroups <- 3 #number of dataframes to read
datacols <- 3 #number of columns to read
fulldata <- list()
for (i in 1:ngroups) {
  nskip <- (datacols+1)*(i-1)
  cols.to.read <- c(rep("NULL", nskip), rep(NA, datacols), rep("NULL", (datacols+1)*(ngroups-i+1)-1)) #creates a list of NULLs and NAs. NULLs = don't read, NA = read
  fulldata[[i]] <- read.csv("test.csv", colClasses=cols.to.read)
}

结果:

fulldata
[[1]]
  h1 h2 h3
1  1  6  3
2  2  1  1
3  3  2  6

[[2]]
  h1.1 h2.1 h3.1
1    1    8    8
2    6    5    8
3    1    2    3

[[3]]

  h1.2 h2.2 h3.2
1    1    5    2
2    1    3    1
3    1    2    5

这有效,但我相信只读一次文件的答案会更快,因为一遍又一遍地读同一个文件并不像最佳程序。

答案 2 :(得分:0)

首先将所有数据读入一个大型数据框:

maindf <- read.table(yourfile)

假设n是csv文件中的数据帧数:

for (i in 0:n-1){
  assign(paste0("df",i+1),maindf[,(1+4*i):(4+4*i)])
}

结果应该是n个可以像这样访问的数据帧:df1,df2,... dfn。 我没有测试它,因为没有提供样本数据。

相关问题