将导入的csv数据保存在向量 - R中 [英] Save imported csv data in vector - R

查看:388
本文介绍了将导入的csv数据保存在向量 - R中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 read.csv(file.csv)$ V1 可能有助于将导出的表分成列,但我的数据组织在一个行因此我想从e lement [1] [1] - > ...->元素[n] [n]中按顺序记录元素。任何想法如何可以在R中实现?



更新:
一旦导入mydata看起来像:

  dat  dat 
[,1] [,2] [,3] [,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

期望的输出将是矢量:c(1,2,3,4,5,6,7 ...)

解决方案

使用代码我提供了一个简单的解决方案可以提取简单的行,但它看起来太容易,也许我错过了一些。

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



编辑



我的解决方案效果很好,但效率不高。这里我有一个改进的循环版本,所以你可以在一个命令分开存储对象。



首先定义元素将是对象的名称:

  val <-c(1:3)
nam< - new_dat_
 <$ c $> 

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

之后,您将看到3个名为 new_dat_1的元素,new_dat_2,new_dat_3val每一个都包含一行dat。这个解决方案可以是非常有用的,如果你必须提取几行,而不只是一个,输出:

  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


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.....)

解决方案

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

这篇关于将导入的csv数据保存在向量 - R中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆