R语言 为每个现有行添加具有多个值的新列

bnlyeluc  于 2023-02-10  发布在  其他
关注(0)|答案(2)|浏览(138)

我有一个示例df:

df <- data.frame(
  col1 = c(1,2,3),
  col2 = c('A','F','Z'),
  col3 = c('R', 'E', 'P')
)

  col1 col2 col3
1    1    A    R
2    2    F    E
3    3    Z    P

我想创造这个:

df2 <- data.frame(
  col1 = c(1,1,2, 2, 3, 3),
  col2 = c('A', 'A', 'F', 'F', 'Z', 'Z'),
  col3 = c('R','R', 'E','E', 'P','P'),
  col4 = c('Total', "Average", 'Total', "Average", 'Total', "Average"),
  col5 = c('ZZ', 'BB', 'ZZ', 'BB','ZZ', 'BB')
)
  col1 col2 col3    col4 col5
1    1    A    R   Total   ZZ
2    1    A    R Average   BB
3    2    F    E   Total   ZZ
4    2    F    E Average   BB
5    3    Z    P   Total   ZZ
6    3    Z    P Average   BB

我在这里补充道:

col4 = c('Total', 'Average')
col5 = c('ZZ', 'BB')

我可以在两个重复的 Dataframe 中添加列,然后进行rbind,但是有没有更有效的方法呢?

pqwbnv8z

pqwbnv8z1#

使用base R

merge(df, data.frame(col4, col5))
  • 输出
col1 col2 col3    col4 col5
1    1    A    R   Total   ZZ
2    2    F    E   Total   ZZ
3    3    Z    P   Total   ZZ
4    1    A    R Average   BB
5    2    F    E Average   BB
6    3    Z    P Average   BB
gt0wga4j

gt0wga4j2#

您可以使用crossing

tidyr::crossing(df, data.frame(col4, col5))

  col1 col2 col3    col4 col5
1    1    A    R   Total   ZZ
2    1    A    R Average   BB
3    2    F    E   Total   ZZ
4    2    F    E Average   BB
5    3    Z    P   Total   ZZ
6    3    Z    P Average   BB

相关问题