R语言 如何更改使第一行(包括列名)成为一个条目

utugiqy6  于 2023-01-15  发布在  其他
关注(0)|答案(1)|浏览(270)

例如,原始数据集如下

我希望结果是
对于第一行(一个条目)

Arson: 133  
Assault/battery: 11330  
Bomb/guns: 604

对于第二行(一个条目)

Arson: 152  
Assault/battery: 10090  
Bomb/guns: 156

我想换成这个

olmpazwi

olmpazwi1#

我们可以循环across感兴趣的列,循环pastestr_c)列名称(cur_column())和列中的值,然后循环unite列到sep = ", "的单个列中(或者如果需要新行,则使用(\n))

library(dplyr)
library(stringr)
library(tidyr)
dat1 %>%
   transmute(across(Arson:`Crimes against children`,
     ~ str_c(cur_column(), ": ", .x))) %>% 
   unite(keyval, everything(), sep = ", ", na.rm = TRUE)
  • 输出
# A tibble: 2 × 1
  keyval                                                                          
  <chr>                                                                           
1 Arson: 133, Assault/battery: 11330, Bomb/guns: 604, Crimes against children: 504
2 Arson: 152, Assault/battery: 10090, Bomb/guns: 156, Crimes against children: 113

数据

dat1 <- structure(list(Arson = c(133, 152), `Assault/battery` = c(11330, 
10090), `Bomb/guns` = c(604, 156), `Crimes against children` = c(504, 
113)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-2L))

相关问题