用数字替换值 [英] Replace values with numbers

查看:64
本文介绍了用数字替换值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中有三个可能的值, Up, Down或NA。



dim(df)= 61,5



我要用+2替换所有上值



所有要用-2替换下值>

所有NA值都为0



我创建了以下函数,但我不断遇到此错误:

  Binaryexpress<-function(x){
for(i in 1:5){
j< -1
while(j< = 61){
if(x [j,i] == Down){
x [j,i]<--2
j< ;-j + 1

}否则if(x [j,i] == Up){
x [j,i]<-2
j<- j + 1

}否则if(is.na(x [j,i])== TRUE){
x [j,i]<-0
j< -j + 1

}
i<-i + 1
}
}
}

if( x [j,i] == Down){:缺少值,其中TRUE / FALSE需要

我在论坛上也尝试了其他方法,例如-> df [df == NA]<-0,但这也没有用。



编辑::



数据帧看起来像这样:

  x1 x2 x3 x4 x5 
y向上向下不适用NA向上
k向下向上不适用NA
l。 。 。 。 。
m。 。 。 。 。


谢谢大家,

解决方案

您不需要任何这些。

  db [db == Up ]--2 
db [db == Down]<---2
db [is.na(db)]<-0

基本上,您正在数据库(我称为db)中搜索 Up, Down或NA,然后分配2,分别为-2和0。



这会留下所有字符,所以您可以这样做:

  db< -as.data.frame(sapply(db,as.numeric))

在您的评论中,您说它给了您一个因数错误-这意味着您的df就是所有因数。首先解决这个问题:

  db< -as.data.frame(sapply(db,as.character), stringsAsFactors = F)


I have a a dataframe, which has three possible values, "Up", "Down" or NA.

dim(df) = 61,5

I want to replace all "Up" values by +2

All "Down" values by -2

All NA values by 0

I have created the following function but I keep on getting this error:

Binaryexpress <- function(x){
  for(i in 1:5){
  j<-1
while(j<= 61){
  if (x[j,i] == "Down"){
    x[j,i] <- -2
    j <- j+1

  } else if(x[j,i] == "Up"){
    x[j,i] <- 2
    j<- j+1

  }else if(is.na(x[j,i]) == TRUE){
    x[j,i] <- 0
    j<- j+1

  }
  i<- i+1
}
}
}

 Error in if (x[j, i] == "Down") { : missing value where TRUE/FALSE needed

I have tried other methods also on the forum, such as -> df[df == NA] <- 0 , but this has not worked either.

EDIT::

Dataframe looks like this:

 x1    x2    x3    x4    x5
y Up  Down   NA    NA    Up
k Down NA    Up    NA    NA
l .     .    .     .     .
m .     .    .     .     .
.
.

Thank you all in advance,

解决方案

You don't need any of that.

db[db=="Up"] <- 2
db[db=="Down"] <- -2
db[is.na(db)] <- 0

Basically, you're searching your database (which I called db) for "Up", "Down", or NAs, and assigning 2, -2, and 0 respectively.

This leaves you with all characters, so you do this:

db<-as.data.frame(sapply(db,as.numeric))

In your comment you said it gives you a factor error - that means your df is all factors. Fix that by starting out with this:

db<-as.data.frame(sapply(db,as.character),stringsAsFactors = F)

这篇关于用数字替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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