根据字符值将数据帧字符分为几列

时间:2020-03-31 17:27:08

标签: r

是否有一种方法可以根据数据帧中的字符值将数据拆分为多列,例如,我从此数据帧开始

initialData = data.frame(attr = c('a','b','c','d'),type = c('1,2','2','3','2 ,3'))

endData是这样的:

class EmailPage extends StatefulWidget {
  EmailPage({Key key}) : super(key: key);

  @override
  _EmailPageState createState() => _EmailPageState();
}

class _EmailPageState extends State<EmailPage> {

  String _email;

  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Email Page'),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          children: <Widget>[
            EMailTextFormField(
              onSaved: (String email) => _email = email,
            ),
            RaisedButton(
              child: Text('Go'),
              onPressed: (){
                if (_formKey.currentState.validate()) {
                  _formKey.currentState.save();

                  print(_email);
                }
              },
            )
          ],
        ),
      ),
    );
  }
}

我编写了一个接受字符的函数,对其进行正则表达式以查看是否满足条件,然后返回true或false,但是我不确定如何遍历数据帧中的每一行并添加到正确的列

1 个答案:

答案 0 :(得分:2)

在用原始数据集的mtabulateqdapTools拆分'type'列后,我们可以使用strsplit中的cbind

library(qdapTools)
out <- cbind(initialData, 
     mtabulate(strsplit(as.character(initialData$type), ",")) > 0)
names(out)[3:5] <- paste0("Cond", names(out)[3:5])
out
#   attr type Cond1 Cond2 Cond3
#1    a  1,2  TRUE  TRUE FALSE
#2    b    2 FALSE  TRUE FALSE
#3    c    3 FALSE FALSE  TRUE
#4    d  2,3 FALSE  TRUE  TRUE