Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

r - Replace values in data frame with other values according to a rule

I am an beginner in R and don`t find a solution for the following problem. Any help would be really appreciated!

I have a data.frame and want to replace certain values of a column with defined other values.

data.frame

date<-c("19921231","19931231","19941231","19941231","19931231","19941231")
variable<-c("a","a","a","b","b","b")
value<-c(1:6)
dataframe <- data.frame(date,variable,value)

attempt to solve problem

yearend<-c("19921231","19931231","19941231")
year<-c("1992","1993","1994")
map = setNames(yearend,year)
dataframe[] = map[dataframe]

error message

Error in map[dataframe] : invalid subscript type 'list'

The problem is obviously, that it is not a matrix. What is the most efficient way to solve this problem? It should also work if I want to replace "real" character, e.g. "BGSFDS" with "BASF stock".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A nice function is mapvalues() from the plyr package:

require(plyr)
dataframe$newdate <- mapvalues(dataframe$date, 
          from=c("19921231","19931231","19941231"), 
          to=c("1992","1993","1994"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...