简体   繁体   English

数据框R,每隔一行添加

[英]Dataframe R, add every other row

This brief example illustrates the problem. 这个简短的例子说明了这个问题。 I want to add the same information Total and Value after every row in my dataframe. 我想在数据框中的每一行之后添加相同的信息TotalValue The correct ID should be given to every new row. 正确的ID应该分配给每个新行。

data.frame(ID=c('A1','A2'), one=c(1,2), two=c(3,4))
  ID one two
1 A1   1   3
2 A2   2   4

The final results should look like this. 最终结果应如下所示。

data.frame(ID=c('A1','A1','A2','A2'), one=c(1,'Total',2,'Total'), two=c(3,'Value',4,'Value'))
  ID   one   two
1 A1     1     3
2 A1 Total Value
3 A2     2     4
4 A2 Total Value

I found a few related SO questions, but they don't really answer my question. 我发现了一些相关的SO问题,但它们并没有真正回答我的问题。

I'm a bit curious about the usefulness of such a transformations, but this is one way to accomplish it: 我对这种转换的用途有些好奇,但这是完成转换的一种方式:

df <- data.frame(ID=c('A1','A2'), one=c(1,2), two=c(3,4))

library(tidyverse)
df %>%
  mutate(one='Total', two='Value') %>% 
  bind_rows(mutate_all(df, as.character)) %>% 
  arrange(ID, one)

Output: 输出:

  ID   one   two
1 A1     1     3
2 A1 Total Value
3 A2     2     4
4 A2 Total Value

A base R version would be 基本的R版本是

#Create a new dataframe with same rows with `ID` value from df
df1 <- data.frame(ID = df$ID, one='Total', two='Value')

#rbind both the dataframes
df2 <- rbind(df, df1)

#Order the new dataframe based on the ID to get alternating rows
df2[order(df2$ID), ]

#  ID   one   two
#1 A1     1     3
#3 A1 Total Value
#2 A2     2     4
#4 A2 Total Value

data 数据

df <- data.frame(ID=c('A1','A2'), one=c(1,2), two=c(3,4))

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

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