这个简短的例子说明了这个问题。我想在数据框中的每一行之后添加相同的信息Total
和Value
。正确的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
最终结果应如下所示。
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
我发现了一些相关的SO问题,但它们并没有真正回答我的问题。
答案 0 :(得分:3)
我对这种转换的用处有点好奇,但这是完成转换的一种方式:
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)
输出:
ID one two
1 A1 1 3
2 A1 Total Value
3 A2 2 4
4 A2 Total Value
答案 1 :(得分:2)
基本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
数据
df <- data.frame(ID=c('A1','A2'), one=c(1,2), two=c(3,4))