如何将一个字段分成 3 个新列
How to break one field into 3 new columns
下面是数据。期望的结果如下。我将如何着手完成这样的任务?
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
可以使用位置索引作为 sep
in separate
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"
或者可以在 base R
中使用 strsplit
在正则表达式环视中执行此操作以拆分
df1 <- data.frame(firm, comment2)
df1[paste0('comment', letters[1:3])] <- do.call(rbind,
lapply(lst1, `length<-`, max(lengths(lst1))))
下面是数据。期望的结果如下。我将如何着手完成这样的任务?
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
可以使用位置索引作为 sep
in separate
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"
或者可以在 base R
中使用 strsplit
在正则表达式环视中执行此操作以拆分
df1 <- data.frame(firm, comment2)
df1[paste0('comment', letters[1:3])] <- do.call(rbind,
lapply(lst1, `length<-`, max(lengths(lst1))))