ConfusedCoder
ConfusedCoder

Reputation: 1

How to edit r function to not have repeating values in column

I am trying to change the activity column in the beaver2 dataset (prepackaged dataset in R) into a character vector such that the value 0 is replaced with idle and the value 1 is replaced with active. This is what I have tried so far but every row within the column is coming out as active for some reason.

rownames1 <- rownames(beaver2)
for(i in 1:length(rownames1)){
  if(rownames1[i] == "0")
    beaver2$activ[i] = 'idle'
  else beaver2$activ[i] = 'active'
}
print(beaver2)

Upvotes: 0

Views: 94

Answers (2)

SteveM
SteveM

Reputation: 2301

This will work:

status <- c("active", "idle")
beaver2$activ <- status[beaver2$activ+1]

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

Since activ column contains 1/0 value you can use that as an index to subset and directly do :

beaver2$newcol <- c('idle', 'active')[beaver2$activ + 1]

However, I think you have to use for loop here in which case you can do :

beaver2$newcol <- NA

for(i in seq_len(nrow(beaver2))){
  if(beaver2$activ[i] == 0)
    beaver2$newcol[i] = 'idle'
  else beaver2$newcol[i] = 'active'
}

Upvotes: 1

Related Questions