Tim
Tim

Reputation: 71

Move value to from one column to another and replace with NA

I have a column in my data frame called size that has a mix of numbers and characters. I'd like to move all the character values to the next column over and replace them with NA's. Here's what my data looks like now.

size <- c(680,1800,720,"apartment","loft") 
type <- c("apartment","available now","apartment","available now","available jul 20")
data <- cbind(size,type)


     size        type              
[1,] "680"       "apartment"       
[2,] "1800"      "available now"           
[3,] "720"       "apartment"       
[4,] "apartment" "available now"   
[5,] "loft"      "available jul 20"

And this is what I'd like it to look like:

     size        type              
[1,] "680"       "apartment"       
[2,] "1800"      "available now"           
[3,] "720"       "apartment"       
[4,] NA          "apartment"
[5,] NA          "loft"

Unfortunately, there is no uniform value in the type column to call on to help replace the values of size. I was hoping to avoid creating a vector of unique types to call on because those unique values may change. What I wish for is a way to delineate character vs numeric within a diverse column. Any help is greatly appreciated!

Upvotes: 2

Views: 3844

Answers (1)

BrodieG
BrodieG

Reputation: 52647

You can use:

rep.rows <- !grepl("^[0-9]+$", data[ ,"size"])
data[rep.rows, ] <- cbind(NA, data[rep.rows, "size"])

Produces:

     size   type           
[1,] "680"  "apartment"    
[2,] "1800" "available now"
[3,] "720"  "apartment"    
[4,] NA     "apartment"    
[5,] NA     "loft"  

Here we first find which rows have something other than numbers for column 1, and then replace those with the modified data.

Upvotes: 1

Related Questions