Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 从逗号分隔文本到矢量_R - Fatal编程技术网

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重复示例中的答案与您的答案不同,因为数据帧的结构不同