How to read data with variables in lines, in Rstudio?

Asked

Viewed 999 times

4

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

My question is: I have a spreadsheet where each row is a variable and each column is an observation in the time series. I wonder if there is how inside the Rstudio it import without doing its usual reading (each column is a variable and each row is an observation)?

  • You can read the spreadsheet, and then use the function t (transpose) to convert from rows to columns.

2 answers

2

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

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

You’ll have to read with header = FALSE, and then make some modifications to the data.frame read 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 English:

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 it is strongly recommended to change the form of data acquisition, if possible. This organization is not standard "R", it is the most common in data organization.

  • Thanks, guys! Really helped!

1

You can use the transposed 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.