Чтение ZIP-файла с машинно-записанными данными не будет "строиться" в RStudio - PullRequest
0 голосов
/ 25 мая 2020

Резюме: Несмотря на сложность подготовки, решение было очень простым: чтобы построить строку фрейма данных в виде линии, а не решетки, мне нужно было транспонировать данные, чтобы инвертировать x obs из y

Я использую RStudio на компьютере Windows 10.

Я использую оборудование scientifi c для записи измерений в файл csv. Затем я заархивировал несколько файлов и прочитал их в R, используя read.csv. Однако фрейм данных ведет себя странно. Команды length и dim не согласуются, а функция plot выдает ошибки. Поскольку я могу создавать смоделированные данные, которые не вызывают ошибок, я думаю, что проблема заключается либо в том, как машина записывала данные, либо в моей загрузке и обработке данных.

Два файла ZIP находятся в моем Репозиторий stackoverflow (с "Монтерей Джек" в названии): https://github.com/baprisbrey/stackoverflow

Вот мой код для их чтения и обработки:

# Unzip the folders
unZIP <- function(folder){
  orig.directory <- getwd()
  setwd(folder)

  zipped.folders <- list.files(pattern = ".*zip")

  for (i in zipped.folders){
    unzip(i)}
  setwd(orig.directory)

}


folder <- "C:/Users/user/Documents/StackOverflow"

unZIP(folder)

# Load the data into a list of lists

pullData <- function(folder){
  orig.directory <- getwd()
  setwd(folder)


  #zipped.folders <- list.files(pattern = ".*zip")
  #unzipped.folders <- list.files(folder)[!(list.files(folder) %in% zipped.folders)]
  unzipped.folders <- list.dirs(folder)[-1] # Removing itself as the first directory.

  oData <- vector(mode = "list", length = length(unzipped.folders))
  names(oData) <- str_remove(unzipped.folders, paste(folder,"/",sep=""))
  for (i in unzipped.folders) {
    filenames <- list.files(i, pattern = "*.csv")
    #setwd(paste(folder, i, sep="/"))
    setwd(i)
    files <- lapply(filenames, read.csv, skip = 5, header = TRUE, fileEncoding = "UTF-16LE") #Note unusual encoding
    oData[[str_remove(i, paste(folder,"/",sep=""))]] <- vector(mode="list", length = length(files))
    oData[[str_remove(i, paste(folder,"/",sep=""))]] <- files
  }

  setwd(orig.directory) 
  return(oData)
}

theData <- pullData(folder) #Load the data into a list of lists

# Process the data into frames
bigFrame <- function(bigList) {
  #where bigList is theData is the result of pullData

  #initialize the holding list of frames per set
  preList <- vector(mode="list", length = length(bigList))
  names(preList) <- names(bigList)

  # process the data
  for (i in 1:length(bigList)){
    step1 <- lapply(bigList[[i]],  t)  # transpose each data
    step2 <- do.call(rbind, step1)     # roll it up into it's own matrix #original error that wasn't reproduced:  It showed length(step2) = 24048 when i = 1 and dim(step2) = 48 501.  Any comments on why?
    firstRow <- step2[1,]              #holding onto the first row to become the names
    step3 <- as.data.frame(step2)      # turn it into a frame
    step4 <- step3[grepl("µA", rownames(step3)),] # Get rid of all those excess name rows
    rownames(step4) <- 1:(nrow(step4))            # change the row names to rowID's
    colnames(step4)  <- firstRow       # change the column names to the first row steps
    step4$ID <- rep(names(bigList[i]),nrow(step4)) # Add an I.D. column
    step4$Class[grepl("pos",tolower(step4$ID))] <- "Yes"  # Add "Yes" class
    step4$Class[grepl("neg",tolower(step4$ID))] <- "No"  # Add "No" class
    preList[[i]] <- step4  
  }

  #  bigFrame <- do.call(rbind, preList) #Failed due to different number of measurements (rows that become columns) across all the data sets
  #  return(bigFrame)

  return(preList) # Works!


}


frameList <- bigFrame(theData) 

monterey <- rbind(frameList[[1]],frameList[[2]])

# Odd behaviors
dim(monterey)    #48 503
length(monterey) #503 #This is not reproducing my original error of length = 24048

rowOne <- monterey[1,1:(ncol(monterey)-2)]

plot(rowOne) #Error in plot.new() : figure margins too large

#describe the data
quantile(rowOne, seq(0, 1, length.out = 11) )
quantile(rowOne, seq(0, 1, length.out = 11) ) %>% plot #produces undesired lattice plot


# simulate the data
doppelganger <- sample(1:20461,501,replace = TRUE)
names(doppelganger) <- names(rowOne)

# describe the data
plot(doppelganger) #Successful scatterplot.  (With my non-random data, I want a line where the numbers in colnames are along the x-axis)
quantile(doppelganger, seq(0, 1, length.out = 11) ) #the random distribution is mildly different
quantile(doppelganger, seq(0, 1, length.out = 11) ) %>% plot # a simple line of dots as desired

# investigating structure

str(rowOne) # results in a dataframe of 1 observation of 501 variables.  This is a correct interpretation.
str(as.data.frame(doppelganger)) # results in 501 observations of 1 variable.  This is not a correct interpretation but creates the plot that I want.

How do I convert the rowOne to plot like doppelganger?

Похоже, одна из моих ошибок заключается в том, что не удается воспроизвести, когда призывы к «тусклому» и «длинному» явно расходятся. Однако я не понимаю, почему функция "plot" создает график решетки на моих обработанных данных и линию точек на моих смоделированных данных.

Я бы хотел построить каждую строку данных как линия. (Далее, вне рамок этого вопроса, я хотел бы классифицировать данные с помощью adaboost. Меня беспокоит, что если «сюжет» ведет себя странно, то классификатор не будет работать.)

Любые советы или предложения, объяснения или советы были бы весьма признательны.

Изменить: исследование структуры с помощью ("str") двух примеров объясняет разницу между графиками. Я предполагаю, что мой измененный вопрос: как мне переключаться между двумя структурами, чтобы можно было построить линию (например, doppelganger) вместо решетки (например, rowOne)?

1 Ответ

0 голосов
/ 25 мая 2020

Я отвечаю на свой вопрос. Я оставляю часть о несоответствии между «длиной» и «тусклостью», поскольку не могу привести воспроизводимый пример. Однако я рад оставить комментарий.

Ответ состоит в том, что для создания моего графика мне просто нужно транспонировать строку следующим образом:

rowOne %>% t() %>% as.data.frame() %>% plot

Это инвертирует структура от одного наблюдения 501 переменной до 501 obs одной переменной выглядит следующим образом: моя "сюжетная" проблема.

...