且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用数字替换值

更新时间:2022-10-20 19:39:01

您不需要任何这些。

  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)