How to read data with variables in rows, in RStudio?

3

I'm starting with the R language in Rstudio. I am an advanced user of MATLAB but with difficulties in R.

My question is: I have a worksheet where each row is a variable and each column is an observation in the time series. I would like to know if there is how to import into RStudio without doing its usual reading (each column is a variable and each row is an observation)?

    
asked by anonymous 16.01.2016 / 16:30

2 answers

1

If you say "in RStudio" refers to the option via the menu (Tools> Import Dataset), it is not possible. This menu only creates a snippet to read the data, according to the parameters you configure.

As the @carlosfigueira mentioned, what you need is the transposition function, t() . After reading just be careful with the names of the columns and the type of object.

You will have to read with header = FALSE , and then make some modifications to the read date.frame to leave it in the correct form. I also recommend using stringsAsFactors = FALSE . For example, considering that you saved the spreadsheet in csv from MS Excel in Portuguese:

csvtext <- "Var1;1,2;1,5;1,6
            Var2;2;4;6
            Var3;7;8;9,2"

dat1 <- read.csv2(text = csvtext, header = FALSE, stringsAsFactors = FALSE)
# Você usaria read.csv2(file = "pasta/arquivo.csv", ...)
dat2 <- t(dat1[, -1])    
dat3 <- as.data.frame(dat2)

rownames(dat3) <- NULL
colnames(dat3) <- dat1[, 1]

dat3
#  Var1             Var2             Var3
#  1.2                2              7.0
#  1.5                4              8.0
#  1.6                6              9.2

str(dat3)
#'data.frame':  3 obs. of  3 variables:
# $ Var1            : num  1.2 1.5 1.6
# $             Var2: num  2 4 6
# $             Var3: num  7 8 9.2

Although I strongly recommend changing the way the data is acquired, if at all possible. This organization is not the "R" standard, it is the most common organization of data.

    
24.01.2016 / 00:12
0

You can use transpose of input data:

mdat <- matrix(c(1,2,3, 11,12,13), nrow = 2, ncol = 3, byrow = TRUE,
               dimnames = list(c("row1", "row2"),
                               c("C.1", "C.2", "C.3")))

dim(mdat)
str(mdat)

mdat2 <- t(mdat)
dim(mdat2)
str(mdat2)
    
14.02.2017 / 11:07