R 从逗号分隔文本到矢量
将数据结构转换为逗号分隔格式:R 从逗号分隔文本到矢量,r,R,将数据结构转换为逗号分隔格式: dframe = data.frame(id=c(1,2,43,53), title=c("text1,color","color,text2","text2","text3,text2")) 要将其转换为每行中都存在或不存在的布尔向量(如预期输出),请执行以下操作: dframe = data.frame(id=c(1,2,43,53), text1=c(1,0,0,0), color=c(1,1,0,0), text2=c(0,1,1,1), text3=c
dframe = data.frame(id=c(1,2,43,53), title=c("text1,color","color,text2","text2","text3,text2"))
要将其转换为每行中都存在或不存在的布尔向量(如预期输出),请执行以下操作:
dframe = data.frame(id=c(1,2,43,53), text1=c(1,0,0,0), color=c(1,1,0,0), text2=c(0,1,1,1), text3=c(0,0,0,1))
我们可以从
tidyverse
中使用分隔行
和排列
:
library(tidyverse)
dframe %>%
separate_rows(title, sep = ",") %>%
mutate(id2 = 1) %>%
spread(title, id2, fill = 0)
输出:
# A tibble: 4 x 5
# Groups: id [4]
id color text1 text2 text3
<dbl> <dbl> <dbl> <dbl> <dbl>
1 1 1 1 0 0
2 2 1 0 1 0
3 43 0 0 1 0
4 53 0 0 1 1
#一个tible:4 x 5
#组别:id[4]
id颜色文本1文本2文本3
1 1 1 1 0 0
2 2 1 0 1 0
3 43 0 0 1 0
4 53 0 0 1 1
@Sotos重复示例中的答案与您的答案不同,因为数据帧的结构不同