0

I have found read.csv("file.csv")$V1 that may help to split exported table into columns but my data is organised in a row-by-row fashion, so I would like to record elements to vector sequentially from element[1][1] ->...->element[n][n]. Any thoughts how it could be accomplished in R?

Update: Once imported mydata looks like:

dat <- matrix(1:27, nrow = 3)
dat
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]    1    4    7   10   13   16   19   22   25
[2,]    2    5    8   11   14   17   20   23   26
[3,]    3    6    9   12   15   18   21   24   27

Desired output would be vector: c(1, 2, 3, 4, 5, 6, 7.....)

Unheilig
  • 16,196
  • 193
  • 68
  • 98
Roman
  • 568
  • 3
  • 8
  • 20
  • Please help us to help you by providing a reproducible example or at least a desired output. If you do not know how to do this topic helps you about reproducible example: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – SabDeM Jun 15 '15 at 00:11
  • 1
    To simply make the rows columns you can use the transpose `t()` function. This can be problematic if your data has different types of variables though. – Molx Jun 15 '15 at 00:11
  • @SabDeM thanks for reply, updated my question. – Roman Jun 15 '15 at 00:18

1 Answers1

2

With the code I provided a simple solution could be to extract simply the row, but it looks too much easy maybe I missed something.

new_dat <- dat[1, ]
new_dat
[1]  1  4  7 10 13 16 19 22 25

Edit

My solution works well but it is not efficient. Here I have an improved loop versions so you can store objects separately in only one command.

First define elements that will be the name of the objects:

val <- c(1:3)
nam <- "new_dat_"

and then extract all elements with the loop.

for(i in 1:nrow(dat)){ assign(paste(nam, val, sep = "")[i], dat[i, ]) }

after that use ls() and you should see 3 elements named new_dat_1","new_dat_2", "new_dat_3" "val" each of them contains one row of your dat. This solution can be very helpful if you have to extract several rows and not just one and lead to this output:

new_dat_3
[1]  3  6  9 12 15 18 21 24 27
new_dat_1
[1]  1  4  7 10 13 16 19 22 25
new_dat_2
[1]  2  5  8 11 14 17 20 23 26
SabDeM
  • 7,050
  • 2
  • 25
  • 38
  • Thanks, simple and nice. I only added new_dat <- as.numeric(dat[1, ]) to get proper vector. – Roman Jun 15 '15 at 00:29