首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在R中的环境中保存csv文件之前,对其进行转置

在R中的环境中保存csv文件之前,对其进行转置
EN

Stack Overflow用户
提问于 2020-04-06 09:11:02
回答 1查看 107关注 0票数 0

我正在处理多个长格式的csv文件。每个文件的列数不同,但行数相同。我试图读取所有文件并将它们合并到一个df中,但我做不到。到目前为止,我使用下面的代码分别读取每个文件:

代码语言:javascript
复制
try <- read.table('input/SMPS/new_format/COALA_SMPS_20200218.txt', #set the file to read
                  sep = ',',  #separator
                  header = F, # do not read the header
                  skip = 17, # skip 17 firdt lines of information 
                  fill = T) %>% #fill all empty spaces in the df
        t()%>%                  #transpose the data
        data.frame()%>%         #make it a df
        select(1:196)           #select the useful data

我的计划是使用与此代码类似的东西,但我不知道在哪里包含转置函数才能使其工作。

代码语言:javascript
复制
smps_files_new <- list.files(pattern = '*.txt',path = 'input/SMPS/new_format/')#Change the path where the files are located
myfiles <-do.call("rbind",  ##Apply the bind to the files
        lapply(smps_files_new, ##call the list
               function(x)  ##apply the next function
                 read.csv(paste("input/SMPS/new_format/", x, sep=''),sep = ',',  #separator
                          header = F, # do not read the header
                          skip = 17, # skip 17 first lines of information 
                          stringsAsFactors = F,
                          fill = T))) ##
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-06 09:14:40

lapply中使用与单个文件相同的代码:

代码语言:javascript
复制
do.call(rbind,  ##Apply the bind to the files
    lapply(smps_files_new, ##call the list
           function(x)  ##apply the next function
             read.csv(paste("input/SMPS/new_format/", x, sep=''),sep = ',',  
                      header = F, # do not read the header
                      skip = 17, # skip 17 first lines of information 
                      stringsAsFactors = FALSE,
                      fill = TRUE) %>%
                      t()%>%        
                      data.frame()%>%
                      select(1:196)))

另一种方法是使用purrr::map_dfmap_dfr而不是lapply + do.call(rbind

代码语言:javascript
复制
purrr::map_df(smps_files_new, 
           function(x)  
             read.csv(paste("input/SMPS/new_format/", x, sep=''),sep = ',',  
                      header = F, 
                      skip = 17, 
                      stringsAsFactors = FALSE,
                      fill = TRUE) %>%
                      t()%>%        
                      data.frame()%>%
                      select(1:196)))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61051580

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档