分割一列字符向量并返回一个列表 [英] Split a column of character vectors and return a list

查看:93
本文介绍了分割一列字符向量并返回一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 dataframe

df <- data.frame(Sl.No = c(1:6),
                 Variable = c('a', 'a,b', 'a,b,c', 'b', 'c', 'b,c'))


   Sl.No   Variable
   1         a
   2         a,b
   3         a,b,c
   4         b
   5         c
   6         b,c

我想在变量列中分离唯一值作为列表

I want to separate the unique values in the variable column as list

myList <- ("a", "b", "c")

我尝试了以下代码:

separator <- function(x) strsplit(x, ",")[[1]][[1]]
unique(sapply(df$Variable, separator))

但这给了我以下输出:

"a"

我需要一些帮助。我已经搜索过,但似乎找不到答案。

I request some help. I have searched but seem unable to find an answer to this.

推荐答案

我们可以拆分 Variable 列的,并获取所有值,并仅选择 unique 的值。

We can split the Variable column at "," and get all the values and select only the unique ones.

unique(unlist(strsplit(df$Variable, ",")))
#[1] "a" "b" "c"

如果变量列是因子,则在使用<$ c之前将其转换为字符$ c> strsplit 。

If the Variable column is factor convert it into character before using strsplit.

这篇关于分割一列字符向量并返回一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆