R帮助将非数字列转换为数字

时间:2018-05-10 22:54:06

标签: r dataframe type-conversion

我正在努力帮助我的朋友,销售总监,了解他的记录呼叫数据。他特别感兴趣的一栏是“处置”。此列有字符串值,我正在尝试将它们转换为数字值(即“未回答”转换为1,“已回答”转换为2等)并删除没有输入值的任何行。我创建了数据框,用作.numeric,创建和删除列/行等无济于事。我只是想运行简单的R代码来给他一些见解。任何和所有的帮助非常感谢。提前谢谢!

P.S。我不确定是否应该提供一些代码,因为有很多微妙的信息(个人电话号码和电子邮件)。

1 个答案:

答案 0 :(得分:0)

或者,您可以使用import React, { Component } from 'react'; import { connect } from 'react-redux'; import FoodComponent from '../../components/FoodComponent/FoodComponent'; import AddComponent from '../../components/Buttons/AddComponent'; import * as actionTypes from '../../store/actions'; import classes from './FoodComponents.scss'; class FoodComponents extends Component { render() { return ( <div> <AddComponent text="Add component" click={this.props.onAddComponent} /> <ul> { this.props.compons.map(component=>( <li key={component.id} > <p className={classes.Component}>{component.co}</p> <input type="text" /> <button onClick={this.props.onEditComponent}> Edit Component </button> <button onClick={()=>this.props.onDeleteComponent(component.id)}> Delete component </button> </li> )) } </ul> </div> ) } } const mapStateToProps = state => { return { compons: state.components } } const mapDispatchToProps = dispatch => { return { onAddComponent: (component) => dispatch({type: actionTypes.ADD_COMPONENT, data: {compToReducer: component}}), onDeleteComponent: (id) => dispatch({type: actionTypes.DELETE_COMPONENT, index: id }), onEditComponent: (component, id) => dispatch({type: actionTypes.EDIT_COMPONENT, data:{componentToReducer: component, index: id}}) } } export default connect(mapStateToProps,mapDispatchToProps)(FoodComponents); 语句创建新列并使用数值填充它。为了说明,我们假设这是您的数据框:

ifelse

现在你定义一个新列,比如df $ Analysis,并根据df $ Disposition中的信息为它分配数字:

df <- data.frame(
  Disposition = c(rep(c("answer", "no answer", "whatever", NA),3)),
  Anything = c(rnorm(12))
)
df

   Disposition    Anything
1       answer  2.54721951
2    no answer  1.07409803
3     whatever  0.60482744
4         <NA>  2.08405038
5       answer  0.31799860
6    no answer -1.17558239
7     whatever  0.94206106
8         <NA>  0.45355501
9       answer  0.01787330
10   no answer -0.07629330
11    whatever  0.83109679
12        <NA> -0.06937357

此方法的优点是可以保持原始信息不变。如果您现在要删除数据框中的Na值,请使用df$Analysis <- ifelse(df$Disposition=="no answer", 1, ifelse(df$Disposition=="answer", 2, 3)) df Disposition Anything Analysis 1 answer 2.54721951 2 2 no answer 1.07409803 1 3 whatever 0.60482744 3 4 <NA> 2.08405038 NA 5 answer 0.31799860 2 6 no answer -1.17558239 1 7 whatever 0.94206106 3 8 <NA> 0.45355501 NA 9 answer 0.01787330 2 10 no answer -0.07629330 1 11 whatever 0.83109679 3 12 <NA> -0.06937357 NA 。注意:这不仅会删除df $ Disposition中的NA值,还会删除任何列中带有NA的任意行

na.omit