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

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

问题描述

我发现 read.csv("file.csv")$V1 可能有助于将导出的表拆分成列,但我的数据是按行组织的,所以我想从 element[1][1] ->...->element[n][n] 顺序记录元素到向量.任何想法如何在 R 中完成?

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?

更新:导入后的 mydata 如下所示:

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

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

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, ]) }

之后使用 ls(),你应该看到 3 个名为 new_dat_1","new_dat_2", "new_dat_3" "val" 的元素,每个元素包含一行您的数据.如果您必须提取多行而不是一行并导致此输出,则此解决方案非常有用:

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天全站免登陆