简体   繁体   English

从数量列中写入新的相同行

[英]Writing new identical rows out of a quantity column

I will explain my problem with an example, we have the following data file in R: 我将通过一个示例来说明我的问题,我们在R中具有以下数据文件:

Species   Diameter    Height   Amount

Oak       1           4        2

Beech     2           12       3

Maple     1.5         7.5      1

Oak       2           9        2

So we have 4 columns ( Species , Diameter , Height and Amount ) and several rows with data. 因此,我们有4列( SpeciesDiameterHeightAmount )和几行数据。 Im trying to write a code to transform the data above to this type: 我试图编写代码将上面的数据转换为这种类型:

Species   Diameter    Height   
Oak       1           4  

Oak       1           4

Beech     2           12  

Beech     2           12 

Beech     2           12 

Maple     1.5         7.5   

Oak       2           9   

Oak       2           9

So the column Amount is now gone but we obtained several identical rows equal to the initial value in the column Amount . 因此,列Amount现在消失了,但是我们获得了几行相同的行,这些行等于列Amount的初始值。

I have a problem implementing this as a code (I am quite new to R programming). 我在将其作为代码实现时遇到了问题(我对R编程很陌生)。 I am thinking in the direction of: 我正在朝以下方向发展:

line <- read.csv (file, nrows = 1, header=FALSE)

while{

    algoritm to add the rowns -> data.frame?

    write.csv(dataframe, fileadress)

}

close(file reader)
close (file writer)

I know this is very basic, but I would be very glad with every tip/idea. 我知道这是非常基本的,但是每一个技巧/想法我都会很高兴。

In R you should read in the whole file, eg into the variable tab . 在R中,您应该阅读整个文件,例如,进入变量tab

Then you can just write tab2 <- tab[ ,-4] . 然后,您只需编写tab2 <- tab[ ,-4]

The -4 means to drop the 4th column, the nothing infront of the comma means 'all rows'. -4表示删除第4列,逗号前面的空表示“所有行”。

Then write the whole table to a file. 然后将整个表写入文件。

Note that it is the preferred way to do something like this in R. Loops are only used when really needed. 请注意,这是在R中执行类似操作的首选方法。仅在真正需要时才使用循环。

(You might also want to look at read.table instead of read.csv) (您可能还希望查看read.table而不是read.csv)

UPDATE: 更新:

As GregF notes this is incomplete. 正如GregF指出的那样,这是不完整的。 I wanted to del this answer but then saw that he had del'ed his too. 我想删除这个答案,但随后看到他也删除了他的答案。 So please see his comment for what needs to be done to have the repetitions you want. 因此,请参阅他的评论以了解需要执行哪些操作才能获得所需的重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM