R语言 如何添加空白行

uyhoqukh  于 2023-09-27  发布在  其他
关注(0)|答案(3)|浏览(125)

在dataframe raw_df中,如何添加空行A_BLANKB_BLANK?结果为wished_df。谢谢你,谢谢

library(tidyverse)
raw_df <- data.frame(category=c('A','A','B','B','C'),
                        value=c(1:5),
                        amount=c(1:5))

wished_df <- data.frame(category=c('A','A','A_BLANK','B','B','B_BLANK','C'),
                        value =c(1,2,NA,3,4,'NA',5),
                        amount =c(1,2,NA,3,4,'NA',5))

l5tcr1uw

l5tcr1uw1#

jpsmith's excellent answer到一个非常相似的问题可以使用,有一些调整:

bad <- c('C_BLANK') # replace with whatever the names are in the real data

raw_df |>
  group_split(category) |>
  map_dfr(~ .x |> add_row(category = paste0(.x$category[1], '_BLANK'), value = NA, amount = NA)) |>
  filter(!category %in% bad)

输出量:

# A tibble: 7 × 3
  category value amount
  <chr>    <int>  <int>
1 A            1      1
2 A            2      2
3 A_BLANK     NA     NA
4 B            3      3
5 B            4      4
6 B_BLANK     NA     NA
7 C            5      5
5vf7fwbs

5vf7fwbs2#

或者将其与all = TRUE合并

wished_df <- merge(
  raw_df,
  data.frame(category = paste(unique(raw_df$category), "BLANK", sep = "_")),
  all = TRUE
)

head(wished_df, -1) # remove the "C_BLANK" row

#   category value amount
# 1        A     1      1
# 2        A     2      2
# 3  A_BLANK    NA     NA
# 4        B     3      3
# 5        B     4      4
# 6  B_BLANK    NA     NA
# 7        C     5      5
okxuctiv

okxuctiv3#

可以使用rbind

rbind(raw_df, NA)

或者,如果您需要类别名称:

df <-data.frame(category = "A", value = NA, amount=NA)
bind_rows(raw_df, df)

相关问题