例如,原始数据集如下
我希望结果是对于第一行(一个条目)
Arson: 133 Assault/battery: 11330 Bomb/guns: 604
对于第二行(一个条目)
Arson: 152 Assault/battery: 10090 Bomb/guns: 156
我想换成这个
olmpazwi1#
我们可以循环across感兴趣的列,循环paste(str_c)列名称(cur_column())和列中的值,然后循环unite列到sep = ", "的单个列中(或者如果需要新行,则使用(\n))
across
paste
str_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))
1条答案
按热度按时间olmpazwi1#
我们可以循环
across
感兴趣的列,循环paste
(str_c
)列名称(cur_column()
)和列中的值,然后循环unite
列到sep = ", "
的单个列中(或者如果需要新行,则使用(\n
))数据