user5873893
user5873893

Reputation:

How to change a string row value?

I would like to change some values of some particular rows. According to previous questions that seemed straight forward with df[df$column=="value",]<-"new value" However I get error character string is not in a standard unambiguous format applying that:

Some data:

dates <- seq(as.Date("2015-02-13"), as.Date("2015-02-22"), by = "days")
b <- c("one","one","two","two","four","four","one","one","five","five")
c <- c(20,30,26,20,30,40,5,10,4,0)
d <- c(11,2233,12,2,22,13,23,23,100,1)
df <- data.frame(dates,b,c,d)

I just would like change all ones to seven:

df[df$b=="one",]<-"seven"

character string is not in a standard unambiguous format

Upvotes: 1

Views: 2592

Answers (2)

cory
cory

Reputation: 6659

Two things... stringsAsFactors and the assignment.

I've pretty much gotten used to using stringsAsFactors=FALSE any time I use read.csv or read.* in general and data.frame. It's burned me so many times, and sometimes it's completely silent with no warnings or errors when it does burn you.

dates <- seq(as.Date("2015-02-13"), as.Date("2015-02-22"), by = "days")
b <- c("one","one","two","two","four","four","one","one","five","five")
c <- c(20,30,26,20,30,40,5,10,4,0)
d <- c(11,2233,12,2,22,13,23,23,100,1)
df <- data.frame(dates,b,c,d, stringsAsFactors=FALSE)
df$b[df$b=="one"]<-"seven"

Upvotes: 3

Sotos
Sotos

Reputation: 51582

You can use stringr library,

df$b <- str_replace_all(df$b, "one", "seven")
#        dates     b  c    d
#1  2015-02-13 seven 20   11
#2  2015-02-14 seven 30 2233
#3  2015-02-15   two 26   12
#4  2015-02-16   two 20    2
#5  2015-02-17  four 30   22
#6  2015-02-18  four 40   13
#7  2015-02-19 seven  5   23
#8  2015-02-20 seven 10   23
#9  2015-02-21  five  4  100
#10 2015-02-22  five  0   1

Upvotes: 2

Related Questions