R 如何将一个字段拆分为3个新列
以下是数据。预期结果如下。我将如何着手做这样一项任务R 如何将一个字段拆分为3个新列,r,substring,R,Substring,以下是数据。预期结果如下。我将如何着手做这样一项任务 firm <- c("firm1","firm2","firm3","firm4") comment2 <- c(51,5104,"",510466) list <- data.frame(firm,comment2) name comment2 commenta commentb
firm <- c("firm1","firm2","firm3","firm4")
comment2 <- c(51,5104,"",510466)
list <- data.frame(firm,comment2)
name comment2 commenta commentb commentc
firm1 51 51
firm2 5104 51 04
firm3
firm4 510466 51 04 66
公司可以在单独
library(dplyr)
library(tidyr)
library(stringr)
tibble(firm, comment2) %>%
separate(comment2, into = str_c('comment', letters[1:3]),
sep= c(2, 4), remove = FALSE)
-输出
# A tibble: 4 x 5
# firm comment2 commenta commentb commentc
# <chr> <chr> <chr> <chr> <chr>
#1 firm1 "51" "51" "" ""
#2 firm2 "5104" "51" "04" ""
#3 firm3 "" "" "" ""
#4 firm4 "510466" "51" "04" "66"
您如何做到这一点并保留原始注释字段tact@TimWilcoxremove=FALSE
将执行此操作。默认情况下,这是真的
df1 <- data.frame(firm, comment2)
df1[paste0('comment', letters[1:3])] <- do.call(rbind,
lapply(lst1, `length<-`, max(lengths(lst1))))