lukeg
lukeg

Reputation: 1357

Using the replace function to change value in R

The replace () help info is very basic and contains no examples. Say I have the following

ages <- sample(40:80, 10, replace = T)
weights <- 100 + ages*.2 + rnorm(10, 0 , 20)
type <- sample(letters[1:3], 10, replace = T)
grouping <- data.frame(ages,weights,type)

It may look like

   ages   weights type
1    49  81.27546    c
2    71 116.50149    c
3    67 152.14525    b
4    45 135.75849    c
5    72 114.35790    a
6    46 110.36591    a
7    40 106.16965    c
8    77 126.09591    c
9    44 107.28003    a
10   69  96.06653    b

I want to change the 'type' value in row 9 from 'a' to 'z'. I have looked to use the following commands, but neither has worked

replace(grouping$type[9],values = "z")

OR

grouping$type[9] <- z

Upvotes: 2

Views: 750

Answers (2)

David Arenburg
David Arenburg

Reputation: 92282

Or you can just make data.frame not to convert your character type variables to factors by default, by setting stringsAsFactors = FALSE

grouping <- data.frame(ages,weights,type, stringsAsFactors = FALSE)

Then

grouping$type[9] <- "z"

Will work as expected

Upvotes: 2

Jilber Urbina
Jilber Urbina

Reputation: 61154

You can solve your problem by doing this

levels(grouping$type) <- c(levels(grouping$type), "z")  # adding new level "z"
grouping$type[9] <- "z"                                 # changing a to z 

Upvotes: 2

Related Questions