如何更改字符串行值?

时间:2016-03-04 15:34:39

标签: r

我想更改某些特定行的某些值。根据先前的问题df[df$column=="value",]<-"new value" 但是我收到错误character string is not in a standard unambiguous format 应用它:

一些数据:

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)

我只想把所有的改为七:

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

字符串不是标准的明确格式

2 个答案:

答案 0 :(得分:3)

两件事...... stringsAsFactors和作业。

在我一般使用stringsAsFactors=FALSEread.csvread.*时,我已经习惯使用data.frame了。它烧了我很多次,有时它完全沉默,没有任何警告或错误,当它烧伤你时。

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"

答案 1 :(得分:0)

您可以使用stringr库,

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