【问题标题】:dividing data frame and transposing in a for loop r分割数据帧并在for循环中转置r
【发布时间】:2020-08-27 20:05:59
【问题描述】:

您好,我有一个 csv 文件,我想按每一行拆分,然后为该行数据创建一个新文件,然后转置该数据,最后根据'full_name 列。我可以为第一行编写简单的代码来执行此操作,但是对于在初始 csv 的 331 次迭代或行中执行此操作时,我一无所知

我的代码(适用于第一行)是这样的:

library(rvest)
library(data.table)
library(readr)
library(readxl)
library(tidyverse)

setwd("~/Desktop/Monthly_Reports")

Reports <- read_csv("~/Desktop/Monthly_Reports/REPORTS MASTER - SEPT.csv")

#takes the first row subsets it and renames it based on the value in the name column
Reports1 <- Reports[1,]
Report1_Name <- Reports1$Full_Name[[1]]

#then transposes the data, and makes it easier to read as a list
Reports1 <- transpose(Reports1)
rownames(Reports1) <- colnames(Reports1)
colnames(Reports1) <- rownames(Reports1)

#then binds the list so that it can be exported as data frame and into and individual csv
Reports1 <- as.data.frame(Reports1)
Reports1 <- do.call("rbind", lapply(Reports1, as.data.frame)) 
write.csv(Reports1, paste0(Report1_Name,".csv"))

我想对每一行数据执行 331 次,如果有人可以告诉我如何执行此操作,这似乎很简单,但我已经阅读了很多线程和网站帮助,了解 for 循环、lapply 各种东西和 for不知为何我还在苦苦挣扎

非常感谢

【问题讨论】:

    标签: r loops for-loop


    【解决方案1】:

    我没有数据,所以我无法确认,但这样的事情应该可以工作:

    library(rvest)
    library(data.table)
    library(readr)
    library(readxl)
    library(tidyverse)
    
    setwd("~/Desktop/Monthly_Reports")
    
    Reports <- read_csv("~/Desktop/Monthly_Reports/REPORTS MASTER - SEPT.csv")
    
    #takes the first row subsets it and renames it based on the value in the name column
    for(i in 1:nrow(Reports)){
      Reports1 <- Reports[i,]
      Report1_Name <- Reports1$Full_Name[[1]]
      
      #then transposes the data, and makes it easier to read as a list
      Reports1 <- transpose(Reports1)
      rownames(Reports1) <- colnames(Reports1)
      colnames(Reports1) <- rownames(Reports1)
      
      #then binds the list so that it can be exported as data frame and into and individual csv
      Reports1 <- as.data.frame(Reports1)
      Reports1 <- do.call("rbind", lapply(Reports1, as.data.frame)) 
      write.csv(Reports1, paste0(Report1_Name,".csv"))
    }
    

    【讨论】:

    • 哦,伙计,非常感谢你,我不敢相信这有多么简单。
    猜你喜欢
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 2021-02-09
    相关资源
    最近更新 更多